Jaeilit

Next js Jest Test Setting 본문

TIL

Next js Jest Test Setting

Jaeilit 2023. 1. 8. 18:38
728x90

https://nextjs.org/docs/testing#quickstart-2

 

Testing | Next.js

Learn how to set up Next.js with three commonly used testing tools — Cypress, Playwright, Jest, and React Testing Library.

nextjs.org

 

1. npm 설치

npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom

 

2. jest.config.js 설정하기

 

-- 공식문서의 기본옵션 외에도 커버리지로 테스트 범위를 설정해주는 옵션과 test 시 무시할 파일들,, 필요에 따라 기타 옵션들을 설정해주면 된다.

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

const createJestConfig = nextJest({
  dir: "./",
});

const customJestConfig = {
  moduleDirectories: ["node_modules", "<rootDir>/"],
  testEnvironment: "jest-environment-jsdom",
  setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],

  collectCoverage: true,
  coverageProvider: "v8",
  collectCoverageFrom: [
    "<rootDir>/components/**/*.{jsx,tsx}",
    "<rootDir>/app/**/page.tsx",
    "!**/*.d.ts",
    "!**/node_modules/**",
    "!<rootDir>/out/**",
    "!<rootDir>/.next/**",
    "!<rootDir>/*.config.js",
    "!<rootDir>/coverage/**",
  ],

  testPathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/.next/"],
  testEnvironment: "jsdom",
  transform: {
    "^.+\\.(js|jsx|ts|tsx)$": ["babel-jest", { presets: ["next/babel"] }],
  },
  transformIgnorePatterns: [
    "/node_modules/",
    "^.+\\.module\\.(css|sass|scss)$",
  ],
};

module.exports = createJestConfig(customJestConfig);

옵션에 대해서는 jest 문서에 설명이 있다.

https://jestjs.io/docs/configuration#collectcoverage-boolean

 

Configuring Jest · Jest

The Jest philosophy is to work great by default, but sometimes you just need more configuration power.

jestjs.io

 

3. jest.setup.ts

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

import 한줄이지만 test 할 때 저 셋업이 없으면 toBeDocument() 이런 부분에서 not function 이라는 에러를 발생시킨다.

주의사항 파일 명 jset.setup.ts 를 위의 2번의 jest.config.js 에서 설정을 잘해줘야지 읽는다.

setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],

4. tsconfig.ts 에서도 jest.config.js 설정을 해줘야한다.

tsconfig.js 는 프로젝트를 컴파일 하는 옵션들을 정의하는데 jest.config.js 를 포함해야한다.

 

5. script 명령어

jest --watch 와 coverage 를 script 명령어에 추가

 

6. 간단한 테스트 파일 작성해보기

7. 실행 해보기 (왼쪽은 yarn test 오른쪽은 yarn coverage 이다.)

 

728x90