FrontEngineer JungBam

next.js에서 jest 설정하기 본문

jest

next.js에서 jest 설정하기

정밤톨 2023. 7. 19. 02:02
next.js에서 jest로 테스트를 하기 위한 초기 설정을 알아보자.

 

1. package.json 의존성에 아래 라이브러리 추가하고 npm install 하기

** msw 는 서버 요청에 대한 모킹을 하기 위해 추가한 라이브러리

    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^14.0.0",
    "jest": "^29.6.1",
    "jest-environment-jsdom": "^29.6.1",
    "msw": "^1.2.2",

2. root 폴더에 아래 두가지 설정 파일 추가

// jest.config.js

const nextJest = require("next/jest");

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: "./",
});

// Add any custom config to be passed to Jest
const customJestConfig = {
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
  testEnvironment: "jest-environment-jsdom",
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
// jest.setup.js

import "@testing-library/jest-dom/extend-expect";

3. package.json 에 script에 실행명령어 추가하기

"test": "jest --watch --transformIgnorePatterns \"node_modules/(?!axios)/\"",

* 뒤에 있는 --transfome ~ 이후로는 axios 호환 이슈에 대한 해결방법으로 추가

여기까지 설정하고 나면 정상적으로 테스트가 되는 것을 알 수 있다 :)

:: 초기설정에 대한 자세한 공식문서는 아래 링크 참조

 

Optimizing: Testing | Next.js

Cypress is a test runner used for End-to-End (E2E) and Component Testing. You can use create-next-app with the with-cypress example to quickly get started. Run Cypress for the first time to generate examples that use their recommended folder structure: You

nextjs.org


설정하면서 만난 어이없는 에러

에러 원인 분석 : 초기 설정파일 확장명을 .ts로 변환함에 따른 에러
해당 파일을 jest.config.ts, jest.setup.ts로 확장명을 변경해서 발생한 에러였다......하...

 

반응형
Comments