How to Configure Jest in Next.js and Write Your First Test Case

Jest configuration,  Next.js testing,  React component testing, Testing Library setup JavaScript, unit testing, Jest in Next.js, Writing test cases, Next.js best practices, Test-driven development, Frontend testing tools,
Written by M-Ahmed
Sunday, September 1, 2024 at 6:41 PM
Share Blog on
Learn how to configure Jest in a Next.js project and write your first React component test case. This guide covers step-by-step setup and best practices for seamless testing.

Testing is a critical part of modern web development to ensure that your code functions properly and remains maintainable as your application grows. This article will guide you through configuring Jest (a popular testing framework) in a Next. js project. Also, we will write a basic test case that help you to understand how Jest works with React components in Next. js.

Step 1: Set Up Your Next.js Project

Before configuring Jest, ensure that you have a Next.js project set up. If you haven't created one yet, you can do so with the following command:

npx create-next-app@latest my-nextjs-app
cd my-nextjs-app

Step 2: Install Jest and Testing Dependencies

Next, you'll need to install Jest and some additional packages that help with testing in a React and Next.js environment. Run the following command to install the necessary dependencies:

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

Step 3: Configure Jest

Jest requires some configuration to work seamlessly with Next.js. Create a jest.config.js file in the root of your project and add the following configuration:

import type { Config } from 'jest'
import nextJest from 'next/jest.js'

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
})

// Add any custom config to be passed to Jest
const config: Config = {
  coverageProvider: 'v8',
  testEnvironment: 'jsdom',
  // Add more setup options before each test is run
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)

This configuration does a few things:

  • nextJest({ dir: './' }): This ensures Jest is aware of your Next.js configuration.
  • setupFilesAfterEnv: Points to a setup file where you can include custom Jest configurations.
  • testEnvironment: Specifies jsdom as the environment, which is essential for testing React components.
  • moduleNameMapper: Helps Jest understand alias paths used in your project.

Step 4: Create a Jest Setup File

Create a jest.setup.js file in the root of your project. This file is used to set up any global configuration or import additional Jest matchers. Here's a basic setup:

import '@testing-library/jest-dom;

This import extends Jest with additional matchers provided by Testing Library, such as .toBeInTheDocument().

Step 5: Write Your First Test Case

import React from 'react';

const Home = () => {
  return <h1>Welcome to Next.js!</h1>;
};

export default Home;

Let's create a test file __tests__/index.test.js to test this component:

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

describe('Home', () => {
  it('renders a heading', () => {
    render(<Home />);
    const heading = screen.getByRole('heading', { name: /welcome to next\.js!/i });
    expect(heading).toBeInTheDocument();
  });
});
\

This test checks if the Home component renders a heading with the text "Welcome to Next.js!".

Step 6 : Add Jest Script to package.json

Before you start running tests, you need to add a script to your package.json that will allow you to run Jest easily. Open your package.json file and add the following under the "scripts" section:

"scripts": {
  "test": "jest"
}

Step 7: Run Your Tests

Finally, run your tests with the following command:

npm test
or 
npm run test

Jest will find tests files and execute them as needed. If all goes well, you will notice a passing test as output on your terminal.

Have any questions or need further guidance? Feel free to reach out at info@hexgen.cc Stay updated with the latest tips and best practices—subscribe to our newsletter and keep your Next.js projects at the top of their game!

Conclusion

In this article, we've walked through setting up Jest in a Next.js project and writing a simple test case. With Jest and Testing Library, you can confidently test your React components and ensure your Next.js application remains reliable as it evolves. Happy testing!

Join 5,000+ subscribers
Stay in the loop with everything you need to know.
We care about your data in our privacy policy.