Skip to content

Commit

Permalink
disallow console.error
Browse files Browse the repository at this point in the history
Summary:
This method can be used in a test to ensure that there is no unexpected console errors are logged.

We should use `warning` / `invariant` in the Relay to inform developers about runtime exceptions/errors.

Directly using `console.error` makes the output in the tests very hard to read.

Reviewed By: josephsavona

Differential Revision: D34276063

fbshipit-source-id: 9265b2c701706adde9bcfefddd8614ed9f4b6b26
  • Loading branch information
alunyov authored and facebook-github-bot committed Feb 16, 2022
1 parent 0cfdd54 commit 3738783
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
42 changes: 42 additions & 0 deletions packages/relay-test-utils-internal/consoleError.js
@@ -0,0 +1,42 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+relay
* @flow strict-local
* @format
*/

'use strict';

/* global jest, afterEach */

let installed = false;

/**
* Similar to disallowWarnings.
* This method mocks the console.error and throws in the error is printed in the console.
*/
function disallowConsoleErrors(): void {
if (installed) {
throw new Error('`disallowConsoleErrors` should be called at most once');
}
installed = true;
let errors = [];
jest.spyOn(console, 'error').mockImplementation(message => {
errors.push(`Unexpected \`console.error\`:\n${message}.`);
});
afterEach(() => {
if (errors.length > 0) {
const message = errors.join('\n');
errors = [];
throw new Error(message);
}
});
}

module.exports = {
disallowConsoleErrors,
};
4 changes: 3 additions & 1 deletion packages/relay-test-utils-internal/index.js
Expand Up @@ -12,6 +12,7 @@

'use strict';

const {disallowConsoleErrors} = require('./consoleError');
const describeWithFeatureFlags = require('./describeWithFeatureFlags');
const {
FIXTURE_TAG,
Expand Down Expand Up @@ -50,10 +51,11 @@ module.exports = {
cannotReadPropertyOfUndefined__DEPRECATED,
createMockEnvironment,
describeWithFeatureFlags,
disallowConsoleErrors,
disallowWarnings,
expectToWarn,
expectToWarnMany,
expectWarningWillFire,
disallowWarnings,
FIXTURE_TAG,
generateTestsFromFixtures,
matchers: Matchers,
Expand Down

0 comments on commit 3738783

Please sign in to comment.