From 37387839eb3efe631841b7ff184b4ca9c718e909 Mon Sep 17 00:00:00 2001 From: Andrey Lunyov Date: Wed, 16 Feb 2022 13:56:47 -0800 Subject: [PATCH] disallow console.error 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 --- .../relay-test-utils-internal/consoleError.js | 42 +++++++++++++++++++ packages/relay-test-utils-internal/index.js | 4 +- 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 packages/relay-test-utils-internal/consoleError.js diff --git a/packages/relay-test-utils-internal/consoleError.js b/packages/relay-test-utils-internal/consoleError.js new file mode 100644 index 0000000000000..c1b88560fe87c --- /dev/null +++ b/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, +}; diff --git a/packages/relay-test-utils-internal/index.js b/packages/relay-test-utils-internal/index.js index 09224e71e6f46..83fead4a3edfc 100644 --- a/packages/relay-test-utils-internal/index.js +++ b/packages/relay-test-utils-internal/index.js @@ -12,6 +12,7 @@ 'use strict'; +const {disallowConsoleErrors} = require('./consoleError'); const describeWithFeatureFlags = require('./describeWithFeatureFlags'); const { FIXTURE_TAG, @@ -50,10 +51,11 @@ module.exports = { cannotReadPropertyOfUndefined__DEPRECATED, createMockEnvironment, describeWithFeatureFlags, + disallowConsoleErrors, + disallowWarnings, expectToWarn, expectToWarnMany, expectWarningWillFire, - disallowWarnings, FIXTURE_TAG, generateTestsFromFixtures, matchers: Matchers,