DEV Community

Alex Wardi
Alex Wardi

Posted on

Using Display Name to Debug Prop Type Warnings

For my React testing environment, I use Mocha, Enzyme, and Sinon. When I run my npm test script, Mocha runs and enters "watch" mode.

Recently, I noticed a strange and slightly annoying issue, where my initial test run would display prop type warnings, but successive runs via watched file changes would not.

Note: I am using the min reporter inside my mocha.opts file. Also, the component name shown below is respective to my code base, but we can assume any generic name, i.e. MyComponent.

Here's an example of the test output:

Initial Test Run

Initial test run

Subsequent Test Runs (via watched files)

Subsequent test run

In the second screenshot from above (a test run via a watched file change), I had not fixed the problematic prop types code within the offending component, yet my prop type warning disappeared. Why does this happen? It turns out, this is by design within the React code base. They only warn about props when a "new" component is rendered. Subsequent renders of the same component will NOT display warnings, as to avoid spamming the console or STDOUT.

So how do we fix this? The answer is fairly simple, actually. We can take advantage of the displayName property on the component, and update this within the beforeEach hook for any given suite.

describe('My suite', () => {
    beforeEach(() => {
        MyComponent.displayName = `MyComponent${Math.random().toString()}`;
    });

    // Test code down here...
});

Enter fullscreen mode Exit fullscreen mode

Now, when our tests run, React will interpret the component as "new", since its displayName is changing. You'll see warnings on every test run, rather than just the initial one. Here's an example of the output (cropped from right):

Test results after update

Once you've fixed the warnings, just be sure to remove the displayName code from your tests!

Hopefully this helps you to quickly and somewhat painlessly fix any random PropTypes warnings in your Mocha tests!

References

Github Issue

Top comments (0)