Improve your test assertions and error messages with jest-enzyme
When using Jest and Enzyme to test React applications you can sometimes end up with unclear error messages and assertions that feels a bit uneasy to read. This article shows you how to write better test assertions that yields easy-to-understand error messages, using the assertion library jest-enzyme.
Note: This article assumes that you are somewhat familiar with Jest and Enzyme. If not, take a look at the Jest and Enzyme documentation pages to get started .
An example
Consider the following stateless functional component representing a box.
To verify that the simple Box component works as expected we add the following test suite.
Running the test suite shows that all tests pass, but if we were to change the implementation of the Box component in a way that breaks the tests — it would look something like this.
These error messages doesn’t say much about what has actually gone wrong. In the case of this simple example, it’s not too hard to figure out the cause of failure — but for larger components with a more complex test suite it could require some detective work.
Adding jest-enzyme
To improve these error messages and to introduce some new good-looking assertions, we’ll add the assertion library jest-enzyme to our project. If you are using an older version of Jest or Create React App, take a closer look at the jest-enzyme documentation for further installation instructions.
We can then rewrite our Box component test suite using the new assertions.
Failing tests now result in the following error messages.
Better, am I right?
Jest-enzyme includes a bunch of useful assertions beyond the ones used in this example, such as toHaveStyle()
and toHaveProp()
. Take a look at the full jest-enzyme documentation here.
Side note: It‘s also possible to use expect.extend
to add your own matchers. This could be useful for scenarios where you find yourself doing the same complicated assertions a lot. Read more about this in the jest documentation.