Why does my Jest test of React propTypes break when using multiple unacceptable prop values?

前端 未结 2 1678
隐瞒了意图╮
隐瞒了意图╮ 2021-01-23 10:32

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

2条回答
  •  孤街浪徒
    2021-01-23 11:01

    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.

提交回复
热议问题