Skip to content
This repository was archived by the owner on Sep 1, 2024. It is now read-only.

Commit 7b91db6

Browse files
rufmanljharb
authored andcommitted
[New] 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
1 parent 307a0f5 commit 7b91db6

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

__tests__/PropTypesDevelopmentStandalone-test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,27 @@ describe('PropTypesDevelopmentStandalone', () => {
248248
expectInvalidValidatorWarning(PropTypes.exact({ bar: 'true' }), 'string');
249249
expectInvalidValidatorWarning(PropTypes.exact({ bar: null }), 'null');
250250
});
251+
252+
it('calls the passed in warning logger', () => {
253+
const warningLogger = jest.fn()
254+
const propTypes = {
255+
foo(props, propName, componentName) {
256+
throw new Error('some error');
257+
},
258+
};
259+
const props = {foo: 'foo'};
260+
const returnValue = PropTypes.checkPropTypes(
261+
propTypes,
262+
props,
263+
'prop',
264+
'testComponent',
265+
null,
266+
warningLogger,
267+
);
268+
269+
expect(warningLogger).toBeCalledWith('Failed prop type: some error');
270+
expect(returnValue).toBe(undefined);
271+
});
251272
});
252273

253274
describe('resetWarningCache', () => {
@@ -262,6 +283,7 @@ describe('PropTypesDevelopmentStandalone', () => {
262283
'testComponent',
263284
null,
264285
);
286+
265287
PropTypes.resetWarningCache();
266288
PropTypes.checkPropTypes(
267289
propTypes,

checkPropTypes.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ if (process.env.NODE_ENV !== 'production') {
3939
* @param {?Function} getStack Returns the component stack.
4040
* @private
4141
*/
42-
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
42+
function checkPropTypes(typeSpecs, values, location, componentName, getStack, warningLogger = printWarning) {
4343
if (process.env.NODE_ENV !== 'production') {
4444
for (var typeSpecName in typeSpecs) {
4545
if (has(typeSpecs, typeSpecName)) {
@@ -80,7 +80,7 @@ function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
8080

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

83-
printWarning(
83+
warningLogger(
8484
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
8585
);
8686
}

0 commit comments

Comments
 (0)