From 2b39bb1950f9ddb1b4e760da2d7ef84b7dba7fe5 Mon Sep 17 00:00:00 2001 From: Stephane Rufer Date: Wed, 12 Jul 2017 20:09:24 -0700 Subject: [PATCH] checkPropTypes: add argument that allows external logging 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 #34 --- .../PropTypesDevelopmentStandalone-test.js | 21 +++++++++++++++++++ checkPropTypes.js | 8 +++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/__tests__/PropTypesDevelopmentStandalone-test.js b/__tests__/PropTypesDevelopmentStandalone-test.js index 9684d56..6c60abf 100644 --- a/__tests__/PropTypesDevelopmentStandalone-test.js +++ b/__tests__/PropTypesDevelopmentStandalone-test.js @@ -146,6 +146,27 @@ describe('PropTypesDevelopmentStandalone', () => { expect(console.error.calls.argsFor(0)[0]).toContain('some error'); expect(returnValue).toBe(undefined); }); + + 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(false, 'Failed %s type: %s%s', 'prop', 'some error', ''); + expect(returnValue).toBe(undefined); + }); }); describe('Primitive Types', () => { diff --git a/checkPropTypes.js b/checkPropTypes.js index c2b536f..be5e93f 100644 --- a/checkPropTypes.js +++ b/checkPropTypes.js @@ -27,7 +27,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 = null) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { @@ -51,7 +51,11 @@ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { var stack = getStack ? getStack() : ''; - warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); + if (warningLogger) { + warningLogger(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); + } else { + warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); + } } } }