Next.js 13^ Jest 설정하기, 에러 해결
next.js 에서 jest를 설정하려면 바로 시작할 수 있는 방법도 있지만
next를 설치하고 jest를 추가하는 방법을 기록해보려고 한다.
방법은 어렵지 않고 config, setup ... 등 세팅값만 맞춰주면 바로 jest를 실행하고 개발이 가능했다.
Testing: Jest | Next.js
Learn how to set up Jest with Next.js for Unit Testing and Snapshot Testing.
nextjs.org
Quickstart
$npx create-next-app --example with-jest with-jest-app
$yarn create next-app --example with-jest with-jest-app
$npm create next-app --example with-jest with-jest-app
- 간단한 명령어로 설치가능하지만 설치후에 기존에 Next를 설치하는것과 다르게 다른 설정값들을 정하는게 없었고, tailwindCSS 또한 따로 설치해줘야 했다.
- 폴더구조 또한 src가 없어서 새로 폴더구조를 조금 정리해줘야했다. 이러한 설정들이 귀찮다보니 나는 기존 next를 설치하고 Babel을 사용해서 Jest구조를 새로 정리하는 방법으로 진행했다! 오히려 뭔가 더 좋은것 같음
Next 프로젝트에 Jest 추가
- next.js 12 이후 Jest에 대한 기본 구성이 내장되어있다고 한다. 이제 아래 추가 명령어를 통해 설치할 수 있다.
$yarn add --dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
$npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
설치 후 아래 jest.config.js 파일과 jest.setup.js 파일을 생성해줘야한다.
./jest.config.js
module.exports = {
collectCoverage: true,
// on node 14.x coverage provider v8 offers good speed and more or less good report
coverageProvider: "v8",
collectCoverageFrom: [
"**/*.{js,jsx,ts,tsx}",
"!**/*.d.ts",
"!**/node_modules/**",
"!<rootDir>/out/**",
"!<rootDir>/.next/**",
"!<rootDir>/*.config.js",
"!<rootDir>/coverage/**",
],
moduleNameMapper: {
// Handle CSS imports (with CSS modules)
// https://jestjs.io/docs/webpack#mocking-css-modules
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy",
// Handle CSS imports (without CSS modules)
"^.+\\.(css|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
// Handle image imports
// https://jestjs.io/docs/webpack#handling-static-assets
"^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i": `<rootDir>/__mocks__/fileMock.js`,
// Handle module aliases
"^@/components/(.*)$": "<rootDir>/src/components/$1",
"^@/(.*)$": "<rootDir>/src/$1",
},
// Add more setup options before each test is run
setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
testPathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/.next/"],
testEnvironment: "jsdom",
transform: {
// Use babel-jest to transpile tests with the next/babel preset
// https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
"^.+\\.(js|jsx|ts|tsx)$": ["babel-jest", { presets: ["next/babel"] }],
},
transformIgnorePatterns: [
"/node_modules/",
"^.+\\.module\\.(css|sass|scss)$",
],
};
./jest.setup.js
// version 6 이전
import '@testing-library/jest-dom/extend-expect';
// version 6 이후
import '@testing-library/jest-dom';
- Jest version 6 이후 부터는 extend-expoct가 사라졌다고 한다.
typescript라면 type에러가 발생하기 때문에 따로 설치해줘야함
npm i --save-dev @types/jest
만약 'jestmatchers<htmlelement>' 형식에 'tobeinthedocument' 속성이 없습니다.ts(2339)라는 Error가 발생한다면?
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
-----------아래 줄 추가
// "./jest.setup.js"
],
"exclude": ["./cypress.config.ts", "node_modules", "cypress", "**/*.cy.tsx"]
}
- tsconfig.json 파일의 include 옵션에 jest.setup.js 파일을 넣어줘야한다.
참고
[next.js] 13ver jest setting
jest setting
velog.io
Next.js 환경에서 Jest & React Testing Library 사용하기
Jest 와 RTL(React Testing Library)는 유닛테스트를 위해 흔히 같이 사용된다.다음과 같이 Next.js 프로젝트 환경에서 Jest를 사용할 수 있는 세 가지 환경 설정 방법이 있다.Nextjs 공식 문서에 나와있는 quick
velog.io