Testing Next.js applications is important to make sure the code is good and reliable. Jest and React Testing Library are commonly used for testing React apps, including Next.js ones. Here's an example of how to test a simple Next.js component using Jest and React Testing Library:
Let's say we have a simple component called Button
in a file named Button.js
:
// Button.js
import React from 'react';
const Button = ({ onClick, children }) => {
return (
<button onClick={onClick}>
{children}
</button>
);
}
export default Button;
Now, let's write a test for this component using Jest and React Testing Library. Create a file named Button.test.js
in the same directory as your component:
// Button.test.js
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Button from './Button';
describe('Button component', () => {
it('renders children correctly', () => {
const { getByText } = render(<Button>Hello</Button>);
expect(getByText('Hello')).toBeInTheDocument();
});
it('calls onClick prop when clicked', () => {
const onClickMock = jest.fn();
const { getByText } = render(<Button onClick={onClickMock}>Click me</Button>);
const button = getByText('Click me');
fireEvent.click(button);
expect(onClickMock).toHaveBeenCalledTimes(1);
});
});
In this test file:
We use
describe
to group our test cases for theButton
component.The first test case checks if the component renders its children correctly.
The second test case checks if the
onClick
prop is called when the button is clicked.
To run the tests, you can use the Jest CLI command jest
, which will search for test files with a .test.js
extension or files in a __tests__
directory.
jest
This will execute all tests in your project. If you haven't configured Jest already, you may need to set it up in your Next.js project by installing jest
and @testing-library/react
packages and configuring Jest in your package.json
or adding a jest.config.js
file.
This example shows how to test a basic Next.js component with Jest and React Testing Library. You can use this method to test other components, pages, or features in your Next.js app.