Jest

Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

How to use

Here we use Jest alongside with React Testing Library, Test Renderer, and Redux Mock Store.

Snapshot Testing Example

Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly.

import React from 'react';
import renderer from 'react-test-renderer';
import Link from '../Link.react';

it('renders correctly', () => {
  const tree = renderer
    .create(<Link page="http://www.facebook.com">Facebook</Link>)
    .toJSON();
  expect(tree).toMatchSnapshot();
});

Unit Testing Example

We can select an element with a data-testid properties in the component.

import React from "react";
import Section from "@/page/section";

it("should show Hello World", () => {
  render(<Section />);
  const element = screen.getByTestId(`hello-world`);
  expect(element.textContent).toContain("Hello World");
});

Testing a Component with Redux Store

To test a component with redux stores, we can use redux-mock-store.

Handle Next.js Dynamic Import

If you want to test a component and that component contain a dynamic imports from next/dynamic, we can mock it like this to prevent import errors.

This mocks the dynamic imports to use requireinstead.

To read more about mock functions you can check the Official Jest Documentation.

Last updated

Was this helpful?