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 };