@samitouri / QOS-React / commits / a2ed7a6d96

Make unexpected console.warn() calls fail tests (#10341)

* Make console.warn() calls fail tests * Replace matchers with a more straightforward cleanup

Dan Abramov committed Aug 1, 2017 at 19:53 UTC a2ed7a6d9601013a792706bf3379a2b35d4d7e90
1 file changed +31 -45
scripts/jest/test-framework-setup.js
+31 -45
@@ -7,57 +7,43 @@ if (process.env.REACT_CLASS_EQUIVALENCE_TEST) {
7 } else {
8 var env = jasmine.getEnv();
9
10 - var callCount = 0;
11 - var oldError = console.error;
12 - var newError = function() {
13 - callCount++;
14 - oldError.apply(this, arguments);
15 - };
16 -
17 - console.error = newError;
18 -
10 // TODO: Stop using spyOn in all the test since that seem deprecated.
11 // This is a legacy upgrade path strategy from:
12 // https://github.com/facebook/jest/blob/v20.0.4/packages/jest-matchers/src/spyMatchers.js#L160
13 const isSpy = spy => spy.calls && typeof spy.calls.count === 'function';
14
24 - env.beforeEach(() => {
25 - callCount = 0;
26 - jasmine.addMatchers({
27 - toBeReset() {
28 - return {
29 - compare(actual) {
30 - // TODO: Catch test cases that call spyOn() but don't inspect the mock
31 - // properly.
32 - if (actual !== newError && !isSpy(actual)) {
33 - return {
34 - pass: false,
35 - message: () =>
36 - 'Test did not tear down console.error mock properly.',
37 - };
38 - }
39 - return {pass: true};
40 - },
41 - };
42 - },
43 - toNotHaveBeenCalled() {
44 - return {
45 - compare(actual) {
46 - return {
47 - pass: callCount === 0,
48 - message: () =>
49 - 'Expected test not to warn. If the warning is expected, mock ' +
50 - "it out using spyOn(console, 'error'); and test that the " +
51 - 'warning occurs.',
52 - };
53 - },
54 - };
55 - },
15 + ['error', 'warn'].forEach(methodName => {
16 + var oldMethod = console[methodName];
17 + var newMethod = function() {
18 + newMethod.__callCount++;
19 + oldMethod.apply(this, arguments);
20 + };
21 + newMethod.__callCount = 0;
22 + console[methodName] = newMethod;
23 +
24 + env.beforeEach(() => {
25 + newMethod.__callCount = 0;
26 + });
27 +
28 + env.afterEach(() => {
29 + if (console[methodName] !== newMethod && !isSpy(console[methodName])) {
30 + throw new Error(
31 + 'Test did not tear down console.' + methodName + ' mock properly.'
32 + );
33 + }
34 + if (console[methodName].__callCount !== 0) {
35 + throw new Error(
36 + 'Expected test not to call console.' +
37 + methodName +
38 + '(). ' +
39 + 'If the warning is expected, mock it out using ' +
40 + "spyOn(console, '" +
41 + methodName +
42 + "') and test that the " +
43 + 'warning occurs.'
44 + );
45 + }
46 });
57 - });
58 - env.afterEach(() => {
59 - expect(console.error).toBeReset();
60 - expect(console.error).toNotHaveBeenCalled();
47 });
48
49 var wrapDevMatcher = function(obj, name) {