Writing tests

In this guide, we'll walk through writing test for our custom Strong component in Storybook.

HSDS uses Jest and Enzyme for testing.

Directory

All of HSDS's component test files are scoped in the same directory as the component, example:

hsds-react/
└── components/
└── Strong/
└── Strong.test.js

Base test code

In our Strong.test.js file, we'll need to add:

import React from 'react'
import { mount } from 'enzyme'
import Strong from '../Strong'
describe('classNames', () => {
test('Has default className', () => {
const wrapper = mount(<Strong />)
const el = wrapper.find('Strong')
expect(el.hasClass('c-Strong')).toBe(true)
})
})

mount

HSDS favours mount rendering vs. shallow rendering for testing. The benefits are many. The only downside is mount is slightly slower compared to shallow.

Test development

For test development, open up your terminal and run the following command:

npm run dev

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:

npm run test

This runs through the entire Jest test suite, and generates a coverage report under:

hsds-react/
└── coverage/
└── lcov-report/
└── index.html

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