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.

The setupFilesAfterEnv option tells Jest about our setup file, that we’ve created at the previous step.

Creating our first test

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.

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.

Running tests

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 test 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() vs shallow() vs render()

Enzyme has three rendering methods:

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.

Snapshot testing

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:

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:

test('shows out of cheese error message',()=>{constwrapper=mount(<Pizza/>);expect(wrapper.debug()).toMatchSnapshot();});

Only snapshot a part you’re testing:

test('shows out of cheese error message',()=>{constwrapper=mount(<Pizza/>);consterror=wrapper.find('[data-testid="errorMessage"]').text();expect(error).toMatchInlineSnapshot(`Error: Out of cheese!`);});

Selecting DOM elements for tests

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.

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.

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.

Testing React components

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.

Testing rendering

This kind of test can be useful when your component has several variations and you want to test that a certain prop renders the correct variation.

importReactfrom'react';import{mount}from'enzyme';importPizzafrom'../Pizza';test('contains all ingredients',()=>{constingredients=['bacon','tomato','mozzarella','pineapples'];constwrapper=mount(<Pizzaingredients={ingredients}/>);ingredients.forEach(ingredient=>{expect(wrapper.text()).toMatch(ingredient);});});

Here we’re testing that our Pizza component renders all ingredients passed to a component as a prop.

Testing user interaction

To “simulate” (see “To simulate() or not” above) an event like click or change, call this event’s prop directly and then test the output:

importReactfrom'react';import{mount}from'enzyme';importExpandCollapsefrom'../ExpandCollapse';test('button expands and collapses the content',()=>{constchildren='Hello world';constwrapper=mount(<ExpandCollapseexcerpt="Information about dogs">{children}</ExpandCollapse>);expect(wrapper.text()).not.toMatch(children);wrapper.find({children:'Expand'}).simulate('click');expect(wrapper.text()).toMatch(children);wrapper.update();wrapper.find({children:'Collapse'}).simulate('click');expect(wrapper.text()).not.toMatch(children);});

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.

Testing event handlers

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 of the form or with type="button".

Async tests

Asynchronous operations are the most tricky to test. Often developers give up and add random delays to their tests:

constwait=(time=0)=>newPromise(resolve=>{setTimeout(resolve,time);});test('something async',async()=>{// Run an async operation...awaitwait(100).then(()=>{expect(wrapper.text()).toMatch('Done!');});});

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:

importwaitForExpectfrom'wait-for-expect';test('something async',async()=>{expect.assertions(1);// Run an async operation...awaitwaitForExpect(()=>{expect(wrapper.text()).toMatch('Done!');});});

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.

See the next section for more realistic examples.

Testing network requests and mocks

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:

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:

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 caveats

update() method

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().

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.

act() helper

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.