Enzyme is probably the most popular tool to test React components. And though it has good competition now (see the next article!), it’s still used by many teams.
This is the second article in a series, where we learn how to test React components with Jest and Enzyme and how to apply the best practices we’ve learned in the first article.
Enzyme gives you jQuery-like API to find elements, trigger event handler, and so on. It used to be the de facto tool for testing React components and still very popular. Here I’m not trying to convince you to use Enzyme, but merely sharing my experience with it. We’ll explore a popular alternative, React Testing Library, in the next article in this series.
Some of the Enzyme cons are:
The API surface is too big, you need to know which methods are good and which are not.
Too easy to access component internals.
The API isn’t optimized for modern testing best practices.
First, install all the dependencies including peer dependencies:
You’ll also need babel-jest for Babel and ts-jest for TypeScript. If you’re using webpack, make sure to enable ECMAScript modules transformation for the test environment.
Create a src/setupTests.js file to customize the Jest environment:
Then update your package.json like this:
The setupFilesAfterEnv option tells Jest about our setup file, that we’ve created at the previous step.
The best location for a test is close to the source code. For example, if you have a component at src/components/Button.js, a test for this component could be at src/components/__tests__/Button.spec.js. Jest will find and run this test automatically.
So, let’s create our first test:
Here we’re rendering a paragraph of text using the Enzyme’s mount() method, then testing that a rendered tree contains “Hello Jest!” text using the Enzyme’s text() method and Jest’s toMatch() assert.
Run npm test (or npm t) to run all tests. You’ll see something like this:
Run npm run test:watch to run Jest in watch mode: Jest will run only tests that are related to files changed since the last commit, and Jest will rerun these test any time you change the code. This is how I usually run Jest. Watch mode is fast enough even in large projects, where running all tests takes many minutes.
Run npm run test:coverage to run all tests and generate coverage report. You can find it in the coverage folder.
mount() renders the whole DOM tree and gives you jQuery-like API to access DOM elements inside this tree, simulate events and read text content. I prefer this method most of the time.
render() returns a string with rendered HTML code, similar to the renderToString() method from react-dom. It’s useful when you need to test HTML output. For example, a component that renders Markdown.
shallow() renders only the component itself without its children. I never use it. Imagine, you want to click a button in your feature and see that text somewhere changes, but likely both, the button and the text, will be inside children components, so you’ll end up testing internals like props or state, which should be avoided. See Kent C. Dodds’ article Why I never use shallow rendering for more details.
Jest snapshots work like this: you tell Jest that you want to be sure that output of this component should never change accidentally and Jest saves your component output, called snapshot, to a file:
Every time you, or someone in your team, change your markup Jest will show a diff and ask to update a snapshot if the change was intended.
You can use snapshots to store any values: React tree, strings, numbers, object, and so on
Snapshot testing sounds like a good idea, but has several problems:
easy to commit snapshots with bugs;
failures are hard to understand;
a small change can lead to hundreds of failed snapshots;
we tend to update snapshots without thinking;
coupling with low-level modules;
test intentions are hard to understand;
they give a false sense of security.
Avoid snapshot testing unless you’re testing very short output with clear intent, like class names or error messages, or when you really want to verify that the output is the same.
If you use snapshots keep them short and prefer toMatchInlineSnapshot() over toMatchSnapshot().
For example, instead of snapshotting the whole component output:
Generally your tests should resemble how your users interact with your app. That means you should avoid relying on implementation details, because they can change and you’ll need to update your tests.
Let’s compare different methods of selecting DOM elements:
Selector
Recommended
Notes
button, Button
Never
Worst: too generic
.btn.btn-large
Never
Bad: coupled to styles
#main
Never
Bad: avoid IDs in general
[data-testid="cookButton"]
Sometimes
Okay: not visible to the user, but not an implementation detail, use when better options aren’t available
[alt="Chuck Norris"], [role="banner"]
Often
Good: still not visible to users, but already part of the app UI
[children="Cook pizza!"]
Always
Best: visible to the user part of the app UI
To summarise:
Prefer queries that rely on information visible to the user, like button labels, or to assistive technologies, like image alt attributes or ARIA roles.
Use data-testid when none of the above works.
Avoid implementation details like HTML element or React component names, CSS class names or IDs.
For example, to select this button in a test:
We can either query it by its text content:
Or query it by the test ID:
Both are valid, and both have their downsides:
Text content may change and you’ll need to update your tests. This may not be a problem if your translation library only render string IDs in tests, or if you want your test to work with the actual text users see in the app.
Test IDs clutter your markup with props you only need in tests. Test IDs are also something that users of your app don’t see: if you remove a label from a button, a test with test ID will still pass. You may want to set up something to remove them from the markup you send to your users.
There’s no single perfect method of selecting elements in tests, but some methods are better than some others.
using simulate() method, like wrapper.simulate('click');
calling an event handler prop directly, like wrapper.props().onClick().
Which method to use is a big debate in the Enzyme community.
The name simulate() is misleading: it doesn’t really simulate an event but calls the prop the same way we’d do it manually. These two lines will do almost the same:
There’s one difference when you use Hooks in your components: simulate() will call act() method from Test Utilities to “make your test run closer to how React works in the browser”. You’ll see a warning from React when you call an event handler directly on a component with Hooks.
Most of the time difference between calling an event handler directly (either by calling a prop or with simulate() method) and the real browser behavior isn’t important but in some cases this difference may lead you to misunderstanding of your tests’ behavior. For example, if you simulate() a click on a submit button in a form, it won’t submit the form, like a real submit button would do.
Check out all the examples on CodeSandbox. Unfortunately, CodeSandbox doesn’t fully support Jest and some tests fail there, unless you clone the GitHub repository and run tests locally.
To “simulate” (see “To simulate() or not” above) an event like click or change, call the simulate method and then test the output:
Here we have a component that shows some text when you click the “Expand” button and hides it when you click the “Collapse” button. Our test verifies this behavior.
See “Enzyme caveats” section below for more information on the wrapper.update() method.
See the next section for a more complex example of testing events.
When you unit test a single component, event handlers are often defined in the parent component, and there are no visible changes as a reaction to these events. They also define the API of a component that you want to test.
jest.fn() creates a mock function, or a spy, that allows you to check how many times it was called and with which parameters.
Here we’re using jest.fn() to define a spy for onSubmit prop of our Login component, then we’re filling the form using a technique, described in the previous section, then we’re calling the onSubmit prop on a <form> element and check that the onSubmit function was called only once and it has received login and password.
Firing a form submit handler directly is not ideal, because it may lead to false positives in our test, but that’s the only way we can submit a form with Enzyme. For example, we can’t test that a submit button actually submits the form. Some people think such tests are testing the browser, not our code, and should be avoided. But they are not: there are many ways you can mess up a submit button, like placing it outside the form or with type="button".
Asynchronous operations are the most tricky to test. Often developers give up and add random delays to their tests:
This approach is problematic. The delay will always be a random number. A number that is good enough on a developer’s machine at the time of writing the code. But it can be too long or too short at any other time and on any other machine. When it’s too long, our test will run longer than necessary. When it’s too short, our test will break.
A better approach would be polling: waiting for the desired result, like new text on a page, by checking it multiple times with short intervals, until the expectation is true. The wait-for-expect library does exactly that:
Now our tests will wait as long as necessary but not more.
expect.assertions() method is useful for writing async tests: you tell Jest how many assertions you have in your test, and if you mess up something, like forget to return a Promise from test(), this test will fail.
There are many ways to test components, that send network requests:
dependency injection;
mocking a service module;
mocking a high-level network API, like fetch;
mocking a low-level network API, that catches all ways of making network requests.
I’m not mentioning sending a real network request to a real API as an option here, because it’s slow and fragile. Every network problem or change of the data, returned by the API, may break our tests. Also, you’ll need to have the right data for all test cases — hard to achieve with a real API or a database.
Dependency injection is when you pass a dependency as a function parameter or a component prop, instead of hardcoding it inside a module. This allows you to pass another implementation in a test. Use default function parameters or default component props to define the default implementation, one that should be used in non-test code. That way you won’t have to pass the dependency every time you use a function or a component:
When we use our component without passing the fetchIngredients prop, it’ll use the default implementation:
But in tests we’ll pass a custom implementation, that returns mock data instead of making an actual network request:
Note that we’re wrapping async operations in the act() method here.
Dependency injection is great for unit tests, when you’re rendering a component that accepts an injection directly, but for integration tests need too much boilerplate to pass dependencies to deeply nested components.
That’s where request mocking comes in.
Mocking is similar to dependency injection in a way that you’re also replacing a dependency implementation with your own in a test, but it works on a deeper level: by modifying how either module loading or browser APIs, like fetch, work.
With jest.mock() you can mock any JavaScript module. To make it work in our case, we need to extract our fetching function to a separate module, often called a service module:
Then import it in a component:
And now we can mock it in our test:
We’re using Jest’s mockResolvedValue method to resolve a Promise with a mock data.
Mocking the fetch API is similar to mocking a method, but instead of importing a method and mocking it with jest.mock(), you’re matching a URL and giving a mock response.
Here we’re using mock() method from fetch-mock to return a mock response to any network request matching the given URL pattern. The rest of the test is the same as with dependency injection.
Mocking the network is similar to mocking fetch API but it works on a lower level, so network requests, sent using other APIs, like XMLHttpRequest, will also be mocked.
The code is almost the same as with fetch-mock, but here we’re defining a scope: a mapping of request URLs and mock responses.
query(true) means we’re matching a request with any query parameters, otherwise you can define a specific parameters, like query({quantity: 42}).
scope.isDone() is true when all requests, defined in the scope, were made.
I’d choose between jest.mock() and Nock:
jest.mock() is already available with Jest and you don’t need to set up and learn anything new — it works the same way as mocking any other modules.
Nock has slightly more convenient API than fetch-mock, and debugging tools. It can also record real network request, so you don’t have to hand-craft mock responses.
Enzyme’s update() is a magical thing. That’s how the docs describe it:
Forces a re-render. Useful to run before checking the render output if something external may be updating the state of the component somewhere.
Someone doing something somewhere. I couldn’t find any logic on when you need to use it. So my rule of thumb is: write tests without it until you see stale render output. Then add update() before your expect().
Note, that you can only call update() on the wrapper instance:
And you try to simulate a click on this button in your test:
This won’t work because find() returns two nodes: one for the Button React component, and one for the button HTML element, because the component tree would look like this:
To avoid that, you need to use the Enzyme’s hostNodes() method:
hostNodes() method returns only host nodes: in React DOM host nodes are HTML elements.
Be careful with caching and reusing find() queries in your test like so:
It will fail if you change the input’s value and try to reuse the input variable to test it:
This happens because the input variable still keeps the reference to the initial component tree.
To fix this we need to run the find() query again after we change input’s value:
I usually don’t reuse any queries in my tests, and write little helper functions, like the findInput above, instead. This saves me a lot of debugging time.
Wrap “units” of interaction, like rendering, user events, or data fetching, with the act() method from React Test Utilities to make your tests better resemble how your users will interact with your app.
Enzyme calls the act() method for you in some of its methods, like simulate(), but in some cases you need to use it manually in your tests.
Testing recipes page has a better explanation of the act() method and more examples of its usage.