You might have a nice set of React tests, but are you checking for PropType errors? Wouldn’t it be nice to get failing tests whenever you forget to pass a required prop? Well, today is your lucky day.
You can test that no errors are printed to the console – this verifies that you didn’t forget any required props, among other things. You can use the Sinon library to do this, or your favorite spying library:
Check For Errors In One Test
DRY It Up
However, this code can get repetitive real fast. If you want to DRY it out, extract the code into a module like this:
And then in your tests, import and call that function:
Never Allow Errors
And hey, maybe you want to go one step further and ensure that none of your tests print errors. You could move that assertion into the afterEach block like so:
Then import it, call it, and you’re all set.
Check For Specific Errors
If you’d like to be a little more choosy about which errors you expect, you can check that console.error was called with specific text with a function like this:
There you go: now you can directly test for missing props in your unit tests.
Learning React can be a struggle -- so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, read my book Pure React.
Loved it! Very well written and put together. Love that you focused only on React. Wish I had stumbled onto your book first before I messed around with all those scary "boilerplate" projects.