In an answer to a different SO question about how to test propTypes
in React using Jest, I proposed a solution that mocks console.error
, something othe
Here's a bit of detail on the why, to expand on Andrew Willems' detailed description of the conditions causing the problem.
Note that my explanation here applies to the prop-types
library that Facebook extracted from React recently, specifically when checking props with the checkPropTypes
function it exports.
The checkPropTypes.js module keeps mutable state in the form of an object called loggedTypeFailures
on line 16:
var loggedTypeFailures = {};
Lines 47-50 show how it is used and explain the thinking:
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
When a propType check fails, the message is set as a key on loggedTypeFailures
before logging the error, to track that it has already been logged. The next time a propType fails with the same message, the error.message in loggedTypeFailures
check succeeds and logging is skipped.
Since loggedTypeFailures
is private to the module, there is no way to access or reset it.
If you need to detect propType failures in a more robust way (eg., for unit tests), I published a tiny library that helps: check-prop-types. It checks props the same way as checkPropTypes.js
, but returns the error instead of logging it.