Performance: Jest setup for Next.js
This setup affects the development environment speed and test execution time, indirectly impacting developer productivity and feedback loop speed.
import '@testing-library/jest-dom/extend-expect'; // jest.config.js with moduleNameMapper for CSS and images // Setup file to mock Next.js router // jest.config.js example: // module.exports = { // testEnvironment: 'jsdom', // moduleNameMapper: { // '^.+\\.(css|less|scss)$': 'identity-obj-proxy', // '^.+\\.(jpg|jpeg|png|svg)$': '<rootDir>/__mocks__/fileMock.js' // }, // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], // }; // jest.setup.js example: // import '@testing-library/jest-dom/extend-expect'; // import { useRouter } from 'next/router'; // jest.mock('next/router', () => ({ useRouter: jest.fn() })); import { render } from '@testing-library/react'; import Home from '../pages/index'; test('renders home page', () => { const { getByText } = render(<Home />); expect(getByText('Welcome')).toBeInTheDocument(); });
import '@testing-library/jest-dom/extend-expect'; // No jest.config.js or improper config // Tests run without mocking Next.js features // Example test import { render } from '@testing-library/react'; import Home from '../pages/index'; test('renders home page', () => { const { getByText } = render(<Home />); expect(getByText('Welcome')).toBeInTheDocument(); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No Jest config for Next.js | N/A | N/A | N/A | [X] Bad |
| Proper Jest config with mocks | N/A | N/A | N/A | [OK] Good |
jest.config.js to set options.next.config.js is for Next.js settings, package.json can hold scripts but not full Jest config, and babel.config.js is for Babel.import { render, screen } from '@testing-library/react';
import Home from '../pages/index';
test('renders welcome message', () => {
render(<Home />);
const message = screen.getByText('Welcome to Next.js!');
expect(message).toBeInTheDocument();
});Home component renders the text "Welcome to Next.js!"?Home component and looks for the text "Welcome to Next.js!" on screen.Home component actually renders that text, screen.getByText finds it and expect(...).toBeInTheDocument() passes.test('shows button', () => {
render(<MyButton />);
const btn = screen.getByRole('button');
expect(btn.textContent).toBe('Click me');
});TypeError: screen.getByRole is not a function. What is the most likely cause?screen.getByRole is not a function, meaning screen is undefined or missing that method.screen was not imported from '@testing-library/react', so it is undefined in the test file.screen from '@testing-library/react' -> Option Ajest and @testing-library/react to test Next.js components.jest.config.js file to set Jest options for Next.js environment.__tests__ folder or alongside components, not in pages or public folders.Pass the test and this pattern moves unknown