Skip to content

Commit

Permalink
feat(react): add warning helper (#8021)
Browse files Browse the repository at this point in the history
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
andreancardona and kodiakhq[bot] authored Mar 10, 2021
1 parent 59bfae0 commit 9f1287c
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
42 changes: 42 additions & 0 deletions packages/react/src/internal/__tests__/warning-test.js
Original file line number Diff line number Diff line change
@@ -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();
});
});
29 changes: 29 additions & 0 deletions packages/react/src/internal/warning.js
Original file line number Diff line number Diff line change
@@ -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 };

0 comments on commit 9f1287c

Please sign in to comment.