Skip to content

Commit

Permalink
[New] checkPropTypes: add argument that allows external logging
Browse files Browse the repository at this point in the history
When specified, the argument `warningLogger` will be called with the
same arguments as `warning`. Instead of logging errors to the fbjs
warning logger, we are able to handle them externally.

Fixes facebook#34
  • Loading branch information
rufman authored and ljharb committed Jul 13, 2017
1 parent 307a0f5 commit 7b91db6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
22 changes: 22 additions & 0 deletions __tests__/PropTypesDevelopmentStandalone-test.js
Expand Up @@ -248,6 +248,27 @@ describe('PropTypesDevelopmentStandalone', () => {
expectInvalidValidatorWarning(PropTypes.exact({ bar: 'true' }), 'string');
expectInvalidValidatorWarning(PropTypes.exact({ bar: null }), 'null');
});

it('calls the passed in warning logger', () => {
const warningLogger = jest.fn()
const propTypes = {
foo(props, propName, componentName) {
throw new Error('some error');
},
};
const props = {foo: 'foo'};
const returnValue = PropTypes.checkPropTypes(
propTypes,
props,
'prop',
'testComponent',
null,
warningLogger,
);

expect(warningLogger).toBeCalledWith('Failed prop type: some error');
expect(returnValue).toBe(undefined);
});
});

describe('resetWarningCache', () => {
Expand All @@ -262,6 +283,7 @@ describe('PropTypesDevelopmentStandalone', () => {
'testComponent',
null,
);

PropTypes.resetWarningCache();
PropTypes.checkPropTypes(
propTypes,
Expand Down
4 changes: 2 additions & 2 deletions checkPropTypes.js
Expand Up @@ -39,7 +39,7 @@ if (process.env.NODE_ENV !== 'production') {
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
function checkPropTypes(typeSpecs, values, location, componentName, getStack, warningLogger = printWarning) {
if (process.env.NODE_ENV !== 'production') {
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
Expand Down Expand Up @@ -80,7 +80,7 @@ function checkPropTypes(typeSpecs, values, location, componentName, getStack) {

var stack = getStack ? getStack() : '';

printWarning(
warningLogger(
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
);
}
Expand Down

0 comments on commit 7b91db6

Please sign in to comment.