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.

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:

  • create-react-app README section on “Writing tests”
  • Jest — Getting Started
  • Enzyme API documentation

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:

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

Read more https://medium.com/selleo/testing-react-components-best-practices-2f77ac302d12