Horje
NextJS Jest Testing

Jest is a delightful JavaScript testing framework with a focus on simplicity. It’s widely used with React applications and integrates well with Next.js to provide robust testing capabilities. This article explores how to set up and use Jest for testing in a Next.js application.

Steps to Create an Application with Jest Testing

Step 1: Create a Next.js application

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

Step 2: Install Jest

npm install --save-dev jest

Step 3: Install React Testing Library

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

Step 4: Create Jest configuration, Create a jest.config.js file with the following content

module.exports = {
testPathIgnorePatterns: ["<rootDir>/.next",
"<rootDir>/node_modules"],
setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
testEnvironment: "jsdom",
};

Step 5: Create Jest setup file, Create a jest.setup.js file with the following content

import '@testing-library/jest-dom/extend-expect';

Updated Dependencies in package.json File, Update your package.json to include the necessary scripts and dependencies

"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest"
},
"devDependencies": {
"jest": "^27.0.6",
"@testing-library/react": "^11.2.6",
"@testing-library/jest-dom": "^5.11.9"
}

Folder Structure:

Screenshot-2024-07-30-071117


Example: Here’s an example of a simple test for a Next.js page.

JavaScript
// __tests__/index.test.js
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();
  });
});
JavaScript
// index.js
 
export default function Home() {
  return (
    <div>
      <h1>Home</h1>
    </div>
  )
}

Step 6: run your test

npm run test

Output: When you run the test with npm test, you should see an output similar to this

Screenshot-2024-07-20-085933

Terminal output




Reffered: https://www.geeksforgeeks.org


ReactJS

Related
Next.js Functions: useSelectedLayoutSegment Next.js Functions: useSelectedLayoutSegment
Next.js Functions: useParams Next.js Functions: useParams
Next.js vs Nuxt.js Next.js vs Nuxt.js
How To Add Google Analytics in React? How To Add Google Analytics in React?
Next.js Functions: redirect Next.js Functions: redirect

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
21