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:
Finito
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, check out my Pure React workshop.
Learn to think in React
- 90+ screencast lessons
- Full transcripts and closed captions
- All the code from the lessons
- Developer interviews
Dave Ceddia’s Pure React is a work of enormous clarity and depth. Hats off. I'm a React trainer in London and would thoroughly recommend this to all front end devs wanting to upskill or consolidate.