This site runs best with JavaScript enabled.

Write fewer, longer tests

Software Engineer, React Training, Testing JavaScript Training

Photo by Bailey Zindel


Making tests too short often leads to poor testing practices and way more tests.

Imagine we have this UI that renders a loading spinner until some data is loaded:

1import React from 'react'
2import * as api from './api'
3
4function Course({courseId}) {
5 const [state, setState] = React.useState({
6 loading: false,
7 course: null,
8 error: null,
9 })
10
11 const {loading, course, error} = state
12
13 React.useEffect(() => {
14 setState({loading: true, course: null, error: null})
15 api
16 .getCourseInfo(courseId)
17 .then(
18 data => setState({loading: false, course: data, error: null}),
19 e => setState({loading: false, course: null, error: e}),
20 )
21 }, [courseId])
22
23 return (
24 <>
25 <div role="alert" aria-live="polite">
26 {loading ? 'Loading...' : error ? error.message : null}
27 </div>
28 {course ? <CourseInfo course={course} /> : null}
29 </>
30 )
31}
32
33function CourseInfo({course}) {
34 const {title, subtitle, topics} = course
35 return (
36 <div>
37 <h1>{title}</h1>
38 <strong>{subtitle}</strong>
39 <ul>
40 {topics.map(t => (
41 <li key={t}>{t}</li>
42 ))}
43 </ul>
44 </div>
45 )
46}
47
48export default Course

Here's what that would render (I added a "Re-mount" button so you can try making it re-load. I also made it fail 50% of the time):

Let's talk about testing this component. I'm going to mock out the api.getCourseInfo(courseId) call so we don't actually make any network requests for this test. So here are some of the things we'll need to assert that this component does:

  1. it should show a loading spinner
  2. it should call the getCourseInfo function properly
  3. it should render the title
  4. it should render the subtitle
  5. it should render the list of topics

Then there's the error case (like if the request fails):

  1. it should show a loading spinner
  2. it should call the getCourseInfo function properly
  3. it should render the error message

Many people read that list of requirements for a component and turn those into individual test cases. Maybe you've read about a so-called "only one assertion per test best practice." Let's give that a try:

1// 🛑 THIS IS AN EXAMPLE OF WHAT NOT TO DO...
2import React from 'react'
3import {render, wait, cleanup} from '@testing-library/react/pure'
4import {getCourseInfo} from '../api'
5import Course from '../course'
6
7jest.mock('../api')
8
9function buildCourse(overrides) {
10 return {
11 title: 'TEST_COURSE_TITLE',
12 subtitle: 'TEST_COURSE_SUBTITLE',
13 topics: ['TEST_COURSE_TOPIC'],
14 ...overrides,
15 }
16}
17
18describe('Course success', () => {
19 const courseId = '123'
20 const title = 'My Awesome Course'
21 const subtitle = 'Learn super cool things'
22 const topics = ['topic 1', 'topic 2']
23
24 let utils
25 beforeAll(() => {
26 getCourseInfo.mockResolvedValueOnce(buildCourse({title, subtitle, topics}))
27 })
28
29 afterAll(() => {
30 cleanup()
31 jest.resetAllMocks()
32 })
33
34 it('should show a loading spinner', () => {
35 utils = render(<Course courseId={courseId} />)
36 expect(utils.getByRole('alert')).toHaveTextContent(/loading/i)
37 })
38
39 it('should call the getCourseInfo function properly', () => {
40 expect(getCourseInfo).toHaveBeenCalledWith(courseId)
41 })
42
43 it('should render the title', async () => {
44 expect(await utils.findByRole('heading')).toHaveTextContent(title)
45 })
46
47 it('should render the subtitle', () => {
48 expect(utils.getByText(subtitle)).toBeInTheDocument()
49 })
50
51 it('should render the list of topics', () => {
52 const topicElsText = utils
53 .getAllByRole('listitem')
54 .map(el => el.textContent)
55 expect(topicElsText).toEqual(topics)
56 })
57})
58
59describe('Course failure', () => {
60 const courseId = '321'
61 const message = 'TEST_ERROR_MESSAGE'
62
63 let utils, alert
64 beforeAll(() => {
65 getCourseInfo.mockRejectedValueOnce({message})
66 })
67
68 afterAll(() => {
69 cleanup()
70 jest.resetAllMocks()
71 })
72
73 it('should show a loading spinner', () => {
74 utils = render(<Course courseId={courseId} />)
75 alert = utils.getByRole('alert')
76 expect(alert).toHaveTextContent(/loading/i)
77 })
78
79 it('should call the getCourseInfo function properly', () => {
80 expect(getCourseInfo).toHaveBeenCalledWith(courseId)
81 })
82
83 it('should render the error message', async () => {
84 await wait(() => expect(alert).toHaveTextContent(message))
85 })
86})

I definitely recommend against this approach to testing. There are a few problems with it:

  1. The tests are not at all isolated (read Test Isolation with React)
  2. Mutable variables are shared between tests (read Avoid Nesting when you're Testing)
  3. Asynchronous things can happen between tests resulting in you getting act warnings (for this particular example)

It's notable that the first two points there are applicable regardless of what you're testing. The third is a bit of an implementation detail between jest and act.

Instead, I suggest that we combine the tests like so:

1// ✅ This is an example of what to do
2import React from 'react'
3import {render, wait} from '@testing-library/react'
4import {getCourseInfo} from '../api'
5import Course from '../course'
6
7jest.mock('../api')
8
9afterEach(() => {
10 jest.resetAllMocks()
11})
12
13function buildCourse(overrides) {
14 return {
15 title: 'TEST_COURSE_TITLE',
16 subtitle: 'TEST_COURSE_SUBTITLE',
17 topics: ['TEST_COURSE_TOPIC'],
18 ...overrides,
19 }
20}
21
22test('course loads and renders the course information', async () => {
23 const courseId = '123'
24 const title = 'My Awesome Course'
25 const subtitle = 'Learn super cool things'
26 const topics = ['topic 1', 'topic 2']
27
28 getCourseInfo.mockResolvedValueOnce(buildCourse({title, subtitle, topics}))
29
30 const {getByRole, getByText, getAllByRole, findByRole} = render(
31 <Course courseId={courseId} />,
32 )
33
34 expect(getCourseInfo).toHaveBeenCalledWith(courseId)
35 expect(getCourseInfo).toHaveBeenCalledTimes(1)
36
37 const alert = getByRole('alert')
38 expect(alert).toHaveTextContent(/loading/i)
39
40 const titleEl = await findByRole('heading')
41 expect(titleEl).toHaveTextContent(title)
42
43 expect(getByText(subtitle)).toBeInTheDocument()
44
45 const topicElsText = getAllByRole('listitem').map(el => el.textContent)
46 expect(topicElsText).toEqual(topics)
47})
48
49test('an error is rendered if there is a problem getting course info', async () => {
50 const message = 'TEST_ERROR_MESSAGE'
51 const courseId = '321'
52
53 getCourseInfo.mockRejectedValueOnce({message})
54
55 const {getByRole} = render(<Course courseId={courseId} />)
56
57 expect(getCourseInfo).toHaveBeenCalledWith(courseId)
58 expect(getCourseInfo).toHaveBeenCalledTimes(1)
59
60 const alert = getByRole('alert')
61 expect(alert).toHaveTextContent(/loading/i)
62
63 await wait(() => expect(alert).toHaveTextContent(message))
64})

Now our tests are completely isolated, there are no longer shared mutable variable references, there's less nesting so following the tests is easier, and we will no longer get the act warning from React.

Yes, we've violated that "one assertion per test" rule, but that rule was originally created because testing frameworks did a poor job of giving you the contextual information you needed to determine what was causing your test failures. Now a test failure for these Jest tests will look something like this:

1FAIL src/__tests__/course-better.js
2 ● course loads and renders the course information
3
4 Unable to find an element with the text: Learn super cool things. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
5
6 <body>
7 <div>
8 <div
9 aria-live="polite"
10 role="alert"
11 />
12 <div>
13 <h1>
14 My Awesome Course
15 </h1>
16 <ul>
17 <li>
18 topic 1
19 </li>
20 <li>
21 topic 2
22 </li>
23 </ul>
24 </div>
25 </div>
26 </body>
27
28 40 | expect(titleEl).toHaveTextContent(title)
29 41 |
30 > 42 | expect(getByText(subtitle)).toBeInTheDocument()
31 | ^
32 43 |
33 44 | const topicElsText = getAllByRole('listitem').map(el => el.textContent)
34 45 | expect(topicElsText).toEqual(topics)
35
36 at getElementError (node_modules/@testing-library/dom/dist/query-helpers.js:22:10)
37 at node_modules/@testing-library/dom/dist/query-helpers.js:76:13
38 at node_modules/@testing-library/dom/dist/query-helpers.js:59:17
39 at Object.getByText (src/__tests__/course-better.js:42:10)

And in your terminal that'll all be syntax highlighted as well:

Syntax Highlighted Error Output

Thanks to our amazing tools, identifying which assertion resulted in the failure is trivial. I didn't even tell you what I broke, but I'll bet you'd know where to look if this happened to you! And you can avoid the issues described above. If you'd like to make things even more clear, you can add a code comment above the assertion to explain what is important about the assertion you're making.

Conclusion

Don't worry about having long tests. When you're thinking about your two users and avoid the test user, then your tests will often involve multiple assertions and that's a good thing. Don't arbitrarily separate your assertions into individual test blocks, there's no good reason to do so.

I should note that I wouldn't recommend rendering the same component multiple times in a single test block (re-renders are ok if you're testing what happens on prop updates for example).

The principle:

Think of a test case workflow for a manual tester and try to make each of your test cases include all parts to that workflow. This often results in multiple actions and assertions which is fine.

There's the old "Arrange" "Act" "Assert" model for structuring tests. I typically suggest that you have a single "Arrange" per test, and as many "Act" and "Asserts" as necessary for the workflow you're trying to get confidence about.

Find runnable code for these examples here

Appendix

I'm still getting the act warning, even though I'm using React Testing Library's utilities!

React's act utility is built-into React Testing Library. There are very few times you should have to use it directly if you're using React Testing Library's async utilities:

  1. When using jest.useFakeTimers()
  2. When using useImperativeHandle and calling functions directly that call state updaters.
  3. When testing custom hooks and calling functions directly that call state updaters.

Any other time, you should be covered by React Testing Library. If you're still experiencing the act warning, then the most likely reason is something is happening after your test completes for which you should be waiting.

Here's an example of a test (using the same example as above) suffering from this problem:

1// 🛑 THIS IS AN EXAMPLE OF WHAT NOT TO DO...
2test('course shows loading screen', () => {
3 getCourseInfo.mockResolvedValueOnce(buildCourse())
4 const {getByRole} = render(<Course courseId="123" />)
5 const alert = getByRole('alert')
6 expect(alert).toHaveTextContent(/loading/i)
7})

Here we're rendering the Course and just trying to verify that the loading message shows up properly. The problem is when we render the <Course /> component, it immediately fires an async request. We're correctly mocking that out (which we have to do, otherwise our test will actually make the request). However, our test completes synchronously before the mocked out request has a chance to resolve. When it finally does, our success handler is called which calls the state updater function and we get the act warning.

There are three ways to fix this.

  1. Wait for the promise to resolve
  2. Use React Testing Library's wait utility
  3. Put this assertion in another test (the premise of this article)
1// 1. Wait for the promise to resolve
2// ⚠️ this is an ok way to solve this problem, but there's a better way, read on
3test('course shows loading screen', async () => {
4 const promise = Promise.resolve(buildCourse())
5 getCourseInfo.mockImplementationOnce(() => promise)
6 const {getByRole} = render(<Course courseId="123" />)
7 const alert = getByRole('alert')
8 expect(alert).toHaveTextContent(/loading/i)
9 await act(() => promise)
10})

This is actually not all that bad. I would recommend this if there are no observable changes to the DOM. I had a situation like this in a UI I built where I had implemented an optimistic update (meaning the DOM update happened before the request finished) and therefore had no way to wait for/assert on changes in the DOM.

1// 2. Use React Testing Library's `wait` utility
2// ⚠️ this is an ok way to solve this problem, but there's a better way, read on
3test('course shows loading screen', async () => {
4 getCourseInfo.mockResolvedValueOnce(buildCourse())
5 const {getByRole} = render(<Course courseId="123" />)
6 const alert = getByRole('alert')
7 expect(alert).toHaveTextContent(/loading/i)
8 await wait()
9})

This only really works if the mock you've created resolves immediately, which is most likely (especially if you're using mockResolvedValueOnce). Here you don't have to use act directly, but this test is basically just ignoring everything that happened during that waiting time which is why I don't really recommend this.

The last (and best) recommendation I have for you is to just include this assertion in the other tests of your component. There's not a whole lot of value out of keeping this assertion all by itself.

Discuss on TwitterEdit post on GitHub

Share article
loading relevant upcoming workshops...
Kent C. Dodds

Kent C. Dodds is a JavaScript software engineer and teacher. He's taught hundreds of thousands of people how to make the world a better place with quality software development tools and practices. He lives with his wife and four kids in Utah.