Writing tests
In this guide, we'll walk through writing test for a custom Input component.
HSDS uses Jest as the testing framework and React Testing Library to write the actual tests.
We also have included the User Event package to make writing tests that need simulating user events easier and more readable.
In the past we have used Enzyme for testing, and a lot of tests still uses it, but do try to write your tests using the above.
Tips
  • Test the output of your rendered components, debug is your friend.
  • Avoid testing implementation details (internal state for example) that enzyme tends to encourage.

Directory

All of HSDS's component test files are scoped in the same directory as the component, example:
1
hsds-react/
2
└── components/
3
└── Input/
4
└── Input.test.js
Copied!

Base test code

In our Input.test.js file, we'll need to add:
1
import React from 'react'
2
import { render, waitFor } from '@testing-library/react'
3
import user from '@testing-library/user-event'
4
import Input from '../Input'
5
6
describe('Input', () => {
7
test('Should render', () => {
8
const { getByLabelText } = render(<Input name="user" />)
9
10
expect(getByLabelText('user')).toBeInTheDocument()
11
expect(getByLabelText('user').classList.contains('c-Input')).toBe(true)
12
})
13
14
// Example of a test with user interaction
15
test('Should fire on change event when typing', async () => {
16
const spy = jest.spy()
17
const { getByLabelText } = render(<Input name="user" onChange={spy} />)
18
const input = getByLabelText('user')
19
20
user.type(input, 'hola')
21
22
// You don't always need to "waitFor" after the event simulation
23
await waitFor(() => {
24
expect(input.value).toBe('hola')
25
expect(spy).toHaveBeenCalled()
26
})
27
})
28
})
Copied!

Test development

For test development, open up your terminal and run the following command:
1
npm run dev
Copied!
This fires up Jest in watch mode, and runs tests against modified files (and their associated files).

Code coverage

Coverage report, generated by Jest
To check code coverage, run the following command:
1
npm run test
Copied!
This runs through the entire Jest test suite, and generates a coverage report under:
1
hsds-react/
2
└── coverage/
3
└── lcov-report/
4
└── index.html
Copied!
You can open the index.html in your browser to view the full report.

Coverage

We strive to have as much coverage as posible, and for that purpose we set the threshold at 95% coverage.
Why not 100%? 100% coverage is a false metric and it does not indicate whether your component is properly tested, and while we maintained 100% coverage for a long period we noticed an excessive usage of istanbul ignore directives, this wasn't because of lazyness but because some things are close to impossible to test in the Jest/JSDOM environment or because istanbul couldn't reach the code for some reason.

Next

Let's write some documentation to make sure other folks know how to use Strong.

See also

Last modified 1yr ago