Ask Question

How to setup Jest with Nextjs + TypeScript

The Getting started of jest official doc wasn't much of help since the approach breaks the Nextjs build 🀷



AuthorΒ΄s AnkiCodes image


Last edited on

1 Answer available

Best answer

I found this, which works for me πŸ™Œ
And seems for me much less pain than the other solutions I saw πŸ˜…

Install those dependencies:

yarn add -D @testing-library/jest-dom @testing-library/react @types/jest jest ts-jest ts-node

Add run scripts

"test": "jest",
"test:watch": "jest --watch",

Create file in root `jest.config.ts

import type { Config } from '@jest/types';
export default async (): Promise<Config.InitialOptions> => {
  return {
    preset: 'ts-jest',

    globals: {
      'ts-jest': {
        tsconfig: 'tsconfig.test.json',

    // Automatically clear mock calls and instances between every test
    clearMocks: true,

    // A list of paths to modules that run some code to configure or set up the testing framework before each test
    setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],

    moduleNameMapper: {
      'src/(.*)': '<rootDir>/src/$1',

Create file in root tsconfig.test.json

  "extends": "./tsconfig.json",
  "compilerOptions": {
    "jsx": "react-jsx"