Properly Configuring Jest for React and Next.js
Unit tests are the foundation of modern frontend quality. This guide walks you through setting up Jest and React Testing Library (RTL) in React and Next.js projects with support for TypeScript, SCSS, SVG, and more.
🚀 Installing Jest
npm install --save-dev jest @types/jestGenerate a base config:
npx jest --initWhen prompted:
- ✅ Add test script to package.json
- ✅ Use TypeScript: yes
- ✅ Test environment: jsdom
- ❌ Coverage: no (optional)
- ✅ Use Babel: yes
- ✅ Clear mocks: yes
🔧 Basic jest.config.ts
export default {
clearMocks: true,
testEnvironment: 'jsdom',
coveragePathIgnorePatterns: ['\\node_modules\\'],
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'node'],
moduleDirectories: ['node_modules'],
modulePaths: ['<rootDir>src'],
testMatch: ['<rootDir>src/**/*(*.)@(spec|test).[tj]s?(x)'],
rootDir: '../../',
transformIgnorePatterns: ['node_modules/(?!axios)'],
reporters: [
'default',
[
'jest-html-reporters',
{
publicPath: '<rootDir>/reports/unit',
filename: 'report.html',
inlineSource: true,
},
],
],
};✅ ESLint Integration
Update .eslintrc.js:
env: {
jest: true,
},
rules: {
'max-len': ['error', { ignoreComments: true, code: 125 }],
}🧪 First Test
describe('basic tests', () => {
test('should pass', () => {
expect(true).toBe(true);
});
});⚙️ Jest + Next.js
Install extra packages:
npm install -D jest jest-environment-jsdom @testing-library/jest-dom ts-nodeUpdate jest.config.ts with next/jest:
import { Config } from 'jest';
import nextJest from 'next/jest';
const createJestConfig = nextJest({ dir: './' });
const config: Config = {
clearMocks: true,
testEnvironment: 'jsdom',
coverageProvider: 'v8',
modulePaths: ['<rootDir>src'],
testMatch: ['<rootDir>src/**/*(*.)@(spec|test).[tj]s?(x)'],
reporters: [/* same as before */],
};
export default createJestConfig(config);Add dummy export to fix TS module error:
export {};Run tests:
npm run test:unit🔬 Test Setup
npm install --save-dev @testing-library/react @testing-library/domsetupTests.ts:
import '@testing-library/jest-dom';In jest.config.ts:
setupFilesAfterEnv: ['<rootDir>/config/jest/setupTests.ts']In tsconfig.json:
"include": ["./config/jest/setupTests.ts"]🧪 Example RTL Test
describe('Button', () => {
test('renders correctly', () => {
render(<Button>Click</Button>);
expect(screen.getByText('Click')).toBeInTheDocument();
});
});🎨 SCSS & SVG Setup
npm i identity-obj-proxyIn jest.config.ts:
moduleNameMapper: {
'\.(s?css)$': 'identity-obj-proxy',
}To mock SVGs:
moduleNameMapper: {
'\.(s?css)$': 'identity-obj-proxy',
'\.svg': path.resolve(__dirname, 'jestEmptyComponent.tsx'),
}jestEmptyComponent.tsx:
const JestEmptyComponent = () => <div />;
export default JestEmptyComponent;🧪 SVG Mocks in Next.js
jest.mock('../../assets/icons/arrowLeft.svg', () => () => <div data-testid="svg-mock" />);Alternatively, extend next/jest config dynamically:
const jestConfig = async () => {
const nextJestConfig = await createJestConfig(customJestConfig)();
return {
...nextJestConfig,
moduleNameMapper: {
'\.svg$': path.resolve(__dirname, 'jestEmptyComponent.tsx'),
...nextJestConfig.moduleNameMapper,
},
};
};⚙️ Babel Setup
Install TypeScript and React presets:
npm i @babel/preset-typescript @babel/preset-reactUpdate babel.config.json:
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript",
[
"@babel/preset-react",
{ "runtime": "automatic" }
]
]
}⚡ Async Test Support
npm i -D regenerator-runtimeIn setupTests.ts:
import 'regenerator-runtime/runtime';Jest is flexible, fast, and battle-tested for unit testing in React and Next.js. With proper setup, you’ll catch bugs early and confidently ship reliable code.