From b28c0bf114dd20ee306f9d03e2c99cf2f1838aac Mon Sep 17 00:00:00 2001 From: "Andrea N. Cardona" Date: Mon, 8 Mar 2021 15:54:51 -0700 Subject: [PATCH] feat(react): add warning helper --- .../src/internal/__tests__/warning-test.js | 42 +++++++++++++++++++ packages/react/src/internal/warning.js | 29 +++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 packages/react/src/internal/__tests__/warning-test.js create mode 100644 packages/react/src/internal/warning.js diff --git a/packages/react/src/internal/__tests__/warning-test.js b/packages/react/src/internal/__tests__/warning-test.js new file mode 100644 index 000000000000..9f06e2ae1218 --- /dev/null +++ b/packages/react/src/internal/__tests__/warning-test.js @@ -0,0 +1,42 @@ +/** + * Copyright IBM Corp. 2016, 2018 + * + * This source code is licensed under the Apache-2.0 license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { warning } from '../warning'; + +describe('warning', () => { + test('calls console.warn() when the condition is false', () => { + const spy = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warning(false, 'The message'); + + expect(spy).toHaveBeenCalledWith('Warning: The message'); + spy.mockRestore(); + }); + + test('does not call console.warn() when the condition is true', () => { + const spy = jest.spyOn(console, 'warn').mockImplementation(() => {}); + + warning(true, 'The message'); + + expect(spy).not.toHaveBeenCalled(); + spy.mockRestore(); + }); + + test('throws an error when no message is provided', () => { + expect(() => { + warning(true); + }).toThrow(); + }); + + test('substitutes extra arguments in the message', () => { + const spy = jest.spyOn(console, 'warn').mockImplementation(() => {}); + + warning(false, '%s %s %s', 'a', 'b', 'c'); + + expect(spy).toHaveBeenCalledWith('Warning: a b c'); + spy.mockRestore(); + }); +}); diff --git a/packages/react/src/internal/warning.js b/packages/react/src/internal/warning.js new file mode 100644 index 000000000000..303fa4c98c4c --- /dev/null +++ b/packages/react/src/internal/warning.js @@ -0,0 +1,29 @@ +/** + * Copyright IBM Corp. 2016, 2018 + * + * This source code is licensed under the Apache-2.0 license found in the + * LICENSE file in the root directory of this source tree. + */ + +const emptyFunction = function () {}; + +const warning = __DEV__ + ? function warning(condition, format, ...args) { + if (format === undefined) { + throw new Error( + '`warning(condition, format, ...args)` requires a warning ' + + 'format argument' + ); + } + if (!condition) { + let index = 0; + const message = format.replace(/%s/g, () => { + return args[index++]; + }); + + console.warn('Warning: ' + message); + } + } + : emptyFunction; + +export { warning };