How to setup Jest Unit Test Framework in NextJS

Setting up Jest in a Next.js project involves a few steps to configure Jest, Babel, and other necessary dependencies. Below is a step-by-step guide to help you set up Jest in a Next.js project:

Step 1: Install Jest and Dependencies

  1. Install Jest and related dependencies:bashCopy code
npm install --save-dev jest babel-jest @babel/preset-env @babel/preset-react

@babel/preset-env @babel/preset-react

jest: The testing framework.

babel-jest: Babel integration for Jest.

@babel/preset-env: Babel preset for modern JavaScript.

@babel/preset-react: Babel preset for React.

Step 2: Create Jest Configuration

  1. Create a jest.config.js file in the root of your project:
module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    '\\.(css|less|scss|sass)$': 'identity-obj-proxy',
  },
};
  1. testEnvironment: Set the test environment to jsdom for testing React components.
  2. setupFilesAfterEnv: Specify a setup file for Jest (create this file in the next step).
  3. moduleNameMapper: Mock CSS imports.

Step 3: Create Jest Setup File

  1. Create a jest.setup.js file in the root of your project:
import '@testing-library/jest-dom/extend-expect';
  • This file extends Jest’s expect functions with additional DOM-related matchers.

Step 4: Update scripts in package.json

  1. Update the "scripts" section in your package.json file:
"scripts": {
  "test": "jest"
}

Step 5: Babel Configuration

  1. Create a .babelrc file in the root of your project:
  1. Create a .babelrc file in the root of your project:
{
  "presets": ["next/babel"]
}
  1. This tells Babel to use Next.js presets.

Step 6: Create a Simple Test

  1. Create a test file in the __tests__ directory or alongside your source files. For example, if you have a component in components/MyComponent.js, create a test file at components/__tests__/MyComponent.test.js.
import { render, screen } from '@testing-library/react';
import MyComponent from '../MyComponent';

test('renders MyComponent', () => {
  render(<MyComponent />);
  expect(screen.getByText('Hello, World!')).toBeInTheDocument();
});
  1. This is a basic example of a test for a React component.

Step 7: MyComponent File

// MyComponent.js
import React from 'react';

const MyComponent = () => {
  return (
    <div>
      <h1>Hello, World!</h1>
      {/* Your component content goes here */}
    </div>
  );
};

export default MyComponent;

Step 8: Run Tests

  1. Run the tests using the following command:
npm test
  1. Jest will run all tests in your project.

That’s it! You’ve successfully set up Jest in your Next.js project. You can now expand your tests and use Jest features such as snapshots, mocking, and assertions to thoroughly test your application.