[Next.js] Test

2022-05-08 hit count image

Let's see how to configure Jest and React Testing Library to test the Next.js project based on TypeScript.

Outline

In this blog post, I will introduce how to configure Jest and React Testing Library and how to use them to test the Next.js project based on TypeScript.

You can see the full source code of this blog post on the link below.

Blog list

This blog post is a series. If you want to check other blog posts of the series, see the links below.

Create Next.js project based on TypeScript

To see how to configure Jest and React Testing Library for the testing environment, execute the following command to create a Next.js project with TypeScript.

npx create-next-app --typescript my-app

Install Jest and React Testing Library

To write the test code about the Next.js project based on TypeScript, we need to install Jest and React Testing Library. Execute the command below to install Jest and React Testing Library.

npm install --save-dev jest @testing-library/react @testing-library/jest-dom jest-environment-jsdom

Configure Jest

To write the Jest test code about the Next.js project based on TypeScript, we need to configure Jest. Create the ./jest.setup.js file and modify it like the below.

// Optional: configure or set up a testing framework before each test.
// If you delete this file, remove `setupFilesAfterEnv` from `jest.config.js`

// Used for __tests__/testing-library.js
// Learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect'

This file will be used for the configuration of all Jest test codes or defineing the Mocks.

Next, create the ./jest.config.js file and modify it like the below.

const nextJest = require('next/jest')

const createJestConfig = nextJest({
  dir: './',
})

const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
}

module.exports = createJestConfig(customJestConfig)

The Next.js provides the Jest default configuration since version 12. To use it, we need to modify it to use jest.setup.js that we’ve created above and use next/jest after imporrting it. This configuration makes us to use the Next.js feature(next.config.js, .env, etc) in Jest.

Write test code

Now, let’s write the test code with Jest and React Testing Library. Create the ./tests/index/index.test.tsx file and modify it like the below.

import { render, screen } from '@testing-library/react'
import Home from '../../pages/index'

describe('Home', () => {
  it('renders a heading', () => {
    const { container } = render(<Home />)

    const heading = screen.getByRole('heading', {
      name: /welcome to next\.js!/i,
    })

    expect(heading).toBeInTheDocument()

    expect(container).toMatchSnapshot()
  })
})

I omit the detail of the test code. This test code renders the <Home /> component that we’ve created by the create-next-app command, and check the weclome to next.js! text displayed well on the screen.

Also, we can use toMatchSnapshot to snapshot the rendered HTML.

Script

To check the test code working well,, open the package.json file and modify it like the below.

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start",
  "lint": "next lint",
  "test": "jest --watch",
  "test:ci": "jest --ci"
},
  • test: When changes occur, Jest will exeute the test code automatically.
  • test:ci: This is to execute the test code on CI/CD.

Execute

Next, execute the command below to execute the test code.

npm test

If you don’t have any problem, you can see the following result.

 PASS  tests/index/index.test.tsx
  Home
    ✓ renders a heading (101 ms)

 › 1 snapshot written.
Snapshot Summary
 › 1 snapshot written from 1 test suite.

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 written, 1 total
Time:        2.048 s
Ran all test suites related to changed files.

Watch Usage
 › Press a to run all tests.
 › Press f to run only failed tests.
 › Press p to filter by a filename regex pattern.
 › Press t to filter by a test name regex pattern.
 › Press q to quit watch mode.
 › Press Enter to trigger a test run.

Also, you can see the tests/index/__snapshots__/index.test.tsx.snap file is created and have the result of the snapshot.

Completed

Done! we’ve seen how to configure Jest and React Testing Library to test the Next.js project based on TypeScript. Also, we’ve seen how to write the test code simply.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts