npm init jest@latest
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
jest.config.ts
import type { Config } from 'jest'
import nextJest from 'next/jest.js'
const createJestConfig = nextJest({
dir: './',
})
// custom config
const config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
}
export default createJestConfig(config)
{
moduleNameMapper: {
'^.+\\.module\\.(css|sass|scss)$': '<YOUR-PROJECT-PATH>/node_modules/next/dist/build/jest/object-proxy.js',
'^.+\\.(css|sass|scss)$': '<YOUR-PROJECT-PATH>/node_modules/next/dist/build/jest/__mocks__/styleMock.js',
'^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp)$': '<YOUR-PROJECT-PATH>/node_modules/next/dist/build/jest/__mocks__/fileMock.js',
'^.+\\.(svg)$': '<YOUR-PROJECT-PATH>/node_modules/next/dist/build/jest/__mocks__/fileMock.js',
'@next/font/(.*)': '<YOUR-PROJECT-PATH>/node_modules/next/dist/build/jest/__mocks__/nextFontMock.js',
'next/font/(.*)': '<YOUR-PROJECT-PATH>/node_modules/next/dist/build/jest/__mocks__/nextFontMock.js',
'server-only': '<YOUR-PROJECT-PATH>/node_modules/next/dist/build/jest/__mocks__/empty.js'
},
testPathIgnorePatterns: [ '/node_modules/', '/.next/' ],
transform: {
'^.+\\.(js|jsx|ts|tsx|mjs)$': [
'<YOUR-PROJECT-PATH>/node_modules/next/dist/build/swc/jest-transformer.js',
[Object]
]
},
transformIgnorePatterns: [ '/node_modules/', '^.+\\.module\\.(css|sass|scss)$' ],
watchPathIgnorePatterns: [ '/.next/' ]
}
npm install -D jest @types/jest ts-jest
jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
}
jest.setup.js
require("dotenv").config({ path: ".env.development" })
sizuhiko - Technote - ts-jest が esbuild/swc をトランスフォーマーに使って高速化していた