Testing in Next.js can be done using Jest, a popular JavaScript testing framework. Jest provides a comprehensive solution for testing JavaScript applications, and it integrates well with Next.js. Below are the steps to set up and implement testing in a Next.js project using Jest.
Make sure you have Jest and the required testing libraries installed. You can install them using npm or yarn.
bash# Using npm
npm install --save-dev jest babel-jest @testing-library/react @testing-library/jest-dom identity-obj-proxy
# Using yarn
yarn add --dev jest babel-jest @testing-library/react @testing-library/jest-dom identity-obj-proxy
Create a jest.config.js
file in your project root to configure Jest. Add the following configuration:
javascript// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
'\\.(css|less|scss|sass)$': 'identity-obj-proxy',
},
};
This configuration sets up Jest to use the JSDOM environment, specifies a setup file, and handles CSS imports.
Create a jest.setup.js
file in your project root:
javascript// jest.setup.js
import '@testing-library/jest-dom/extend-expect';
This file extends Jest with additional matchers from @testing-library/jest-dom
.
package.json
Add the following scripts to your package.json
file:
json"scripts": {
"test": "jest"
}
Create a __tests__
folder in your project, or add tests alongside your components/pages with a .test.js
or .spec.js
extension. For example, if you have a file called MyComponent.js
, create a test file named MyComponent.test.js
.
Here's an example test file:
javascript// MyComponent.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import MyComponent from '../path/to/MyComponent';
test('renders MyComponent correctly', () => {
render(<MyComponent />);
expect(screen.getByText('Hello, World!')).toBeInTheDocument();
});
Now, you can run your tests using the following command:
bash# Using npm
npm test
# Using yarn
yarn test
Jest will execute your tests, and you'll see the results in the terminal.
supertest
library.jest.mock
to mock modules or functions.@testing-library/user-event
for simulating user interactions.Remember to refer to the Jest documentation and the Testing Library documentation for more details and advanced testing techniques.