Technology, Tomasz Bąk

Testing React Components Best Practices

The most popular approach to testing React components is to use either Mocha+Chai+Enzyme or Jest+Enzyme. In this article, we will describe our React components testing practices with Jest+Enzyme which are also applicable to Mocha+Chai.

If you are new to testing React components you should read also:

 

TESTS ORGANIZATION

In larger JavaScript projects we put tests close to implementation in __tests__ subfolder. Usually, tests for a component are grouped by structure and behaviour is added on top of it, like: 

 

MINIMAL COMPONENT TEST CONFIRMS COMPONENT RENDERED

Minimal component tests verify that the component renders properly aka smoke testing or “Build Verification Testing”. It can be done with Enzyme or Jest snapshot:

 

 describe(MainSection Component, () => {
 test(render, () => {
 const { wrapper } = setup()
 expect(wrapper).toMatchSnapshot()
 })
 });

The later generates __snapshots__/MainSection.spec.js.snap file.

Changes in snapshots are confirmed locally via ‘u’ in the jest cli and committed to the git repository, so PR reviewer can see them. You can read more on Snapshot Testing

At the moment we limit usage of snapshots to component rendering and complex json (i.e. chart configurations).

 

OK, I TEST RENDERS — WHAT ELSE SHOULD I TEST?

You have to keep in mind that tests are something you have to write and maintain. Writing good tests requires as much craft as creating the application code.

Tests are automated quality assurance and document for developers. The larger the project and team is the more detailed tests you need.

I try to think of future you getting back to this component or refactoring it — what would your expectations from tests be?

  • Isolated — all interactions with external services should are mocked
  • Specific — if change small functionality you would like to get specific test failure message
  • They describe what the system does not how so that you can easily refactor

Let’s go through some practices that we find helpful in achieving those goals.

 

EXPLICIT SETUP() INSTEAD OF BEFOREEACH()

The benefit of using explicit setup() function is that in any test it is clear how the component was initialized. The setup object is also good place to hook some helper functions that interact with wrapper, i.e.

 

 const setup = propOverrides => {
 const props = Object.assign({
 completedCount: 0,
 activeCount: 0,
 onClearCompleted: jest.fn(),
 }, propOverrides)
  
 const wrapper = shallow(<Footer {props} />)
  
 return {
 props,
 wrapper,
 clear: wrapper.find(.clear-completed),
 count: wrapper.find(.todo-count),
 }
 }
  
 describe(count, () => {
 test(when active count 0, () => {
 const { count } = setup({ activeCount: 0 })
 expect(count.text()).toEqual(No items left)
 })
  
 test(when active count above 0, () => {
 const { count } = setup({ activeCount: 1 })
 expect(count.text()).toEqual(1 item left)
 })
 });
view rawsetup.spec.js hosted with ❤ by GitHub

 

TESTING BEHAVIOUR

Testing behaviour in practice it goes down to testing if certain inputs and simulated events result in expected results i.e.

 describe(clear button, () => {
 test(no clear button when no completed todos, () => {
 const { clear } = setup({ completedCount: 0 })
 expect(clear.exists()).toBe(false)
 })
  
 test(on click calls onClearCompleted, () => {
 const { clear, props } = setup({ completedCount: 1 })
 expect(clear.text()).toEqual(Clear completed)
 clear.simulate(click)
 expect(props.onClearCompleted).toBeCalledWith()
 })
 })
view rawbehaviour.spec.js hosted with ❤ by GitHub

You can see how setup() makes writing those tests really fast!

 

USE HELPER FUNCTIONS

Sometimes we have to write many similar tests with just one input variable changed. This can be addressed with helper function that generates test:

 describe(todo list, () => {
 const testFilteredTodos = (filter, todos) => {
 test(`render ${filter} items`, () => {
 const { wrapper, footer } = setup()
 footer.props().onShow(filter)
 expect(wrapper.find(TodoItem).map(node => node.props().todo)).toEqual(todos)
 })
 }
  
 testFilteredTodos(SHOW_ALL, todos)
 testFilteredTodos(SHOW_ACTIVE, ])
 })
view rawgenerate.spec.js hosted with ❤ by GitHub

It reads much batter and is easier to maintain.

 

SUMMARY

Practices described in this article:

  • put tests close to implementation in __tests__ subfolder
  • always start with simple component rendering test aka smoke testing then test behaviour
  • think of future you getting back to this component or refactoring it
  • use explicit setup() and return common shortcut variables with it
  • use helper functions that generates tests

We hope you found this article helpful. You can find working example code at my fork of redux todomvc code at https://github.com/tb/redux/tree/react-testing/examples/todomvc/src/components/__tests__

Author


Avatar

Tomasz Bąk

Tomasz is a Tech Expert with an enormous experience in both back-end and front-end solutions. He ensures that quality processes and automations are carried out through the whole software development cycle.