Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(react): add warning helper #8021

Merged
merged 2 commits into from
Mar 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 };