Properly Configuring Jest for React and Next.js

August, 7th 2025 2 min read

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

bash
1
      npm install --save-dev jest @types/jest
    

Generate a base config:

bash
1
      npx jest --init
    

When 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

ts
12345678910111213141516171819202122
      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:

js
123456
      env: {
  jest: true,
},
rules: {
  'max-len': ['error', { ignoreComments: true, code: 125 }],
}
    

🧪 First Test

ts
12345
      describe('basic tests', () => {
  test('should pass', () => {
    expect(true).toBe(true);
  });
});
    

⚙️ Jest + Next.js

Install extra packages:

bash
1
      npm install -D jest jest-environment-jsdom @testing-library/jest-dom ts-node
    

Update jest.config.ts with next/jest:

ts
123456789101112131415
      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:

ts
1
      export {};
    

Run tests:

bash
1
      npm run test:unit
    

🔬 Test Setup

bash
1
      npm install --save-dev @testing-library/react @testing-library/dom
    

setupTests.ts:

ts
1
      import '@testing-library/jest-dom';
    

In jest.config.ts:

ts
1
      setupFilesAfterEnv: ['<rootDir>/config/jest/setupTests.ts']
    

In tsconfig.json:

json
1
      "include": ["./config/jest/setupTests.ts"]
    

🧪 Example RTL Test

tsx
123456
      describe('Button', () => {
  test('renders correctly', () => {
    render(<Button>Click</Button>);
    expect(screen.getByText('Click')).toBeInTheDocument();
  });
});
    

🎨 SCSS & SVG Setup

bash
1
      npm i identity-obj-proxy
    

In jest.config.ts:

ts
123
      moduleNameMapper: {
  '\.(s?css)$': 'identity-obj-proxy',
}
    

To mock SVGs:

ts
1234
      moduleNameMapper: {
  '\.(s?css)$': 'identity-obj-proxy',
  '\.svg': path.resolve(__dirname, 'jestEmptyComponent.tsx'),
}
    

jestEmptyComponent.tsx:

tsx
12
      const JestEmptyComponent = () => <div />;
export default JestEmptyComponent;
    

🧪 SVG Mocks in Next.js

ts
1
      jest.mock('../../assets/icons/arrowLeft.svg', () => () => <div data-testid="svg-mock" />);
    

Alternatively, extend next/jest config dynamically:

ts
12345678910
      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:

bash
1
      npm i @babel/preset-typescript @babel/preset-react
    

Update babel.config.json:

json
12345678910
      {
  "presets": [
    "@babel/preset-env",
    "@babel/preset-typescript",
    [
      "@babel/preset-react",
      { "runtime": "automatic" }
    ]
  ]
}
    

⚡ Async Test Support

bash
1
      npm i -D regenerator-runtime
    

In setupTests.ts:

ts
1
      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.