포스트

Jest (Nextjs 에서 같이 사용)

테스트 코드란?

테스트 코드란, 소프트웨어의 기능과 동작을 테스트하는데 사용하는 코드이다.

작동을 했을 때, 기능이 정상적으로 동작하는지 확인하는지는 개발 도중에 확인할 수 있는 부분이지만 업데이트와 배포를 하게 되면 생각이 바뀌게 된다.

테스트 코드가 필요한 이유!

ex) 직접했을경우 : 게시판기능 10개 개발 ⇒ 상품 기능 개발 20개 ⇒ 모든 기능 직접 테스트 ⇒ 배포 ⇒ 결제 기능 추가 ⇒ 결제의 모든 테스트 ⇒ 배포 ⇒ 갑자기 결제기능과 상품기능에서 에러 발생!

계속적인 개발을 했을 때, 게시판과 상품 하나씩 다시 클릭 해야됨 기능 하나 추가할때 마다 다른 기능의 모든것을 테스트 해야되는 불상사가 발생한다.

규모가 점점 커지면서 사람이 일일이 모든 다시 테스트를 할 수가 없다! 때문에 테스트 코드가 필요하다.

Jest란

테스트 전용 프레임 워크이다.

Jest 설치방법

1
2
3
4
5
npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom

or

yarn add --dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom

루트에 jest.config.js 파일 생성후

다음과 같이 코드 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import nextJest from "next/jest.js";

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
/** @type {import('jest').Config} */
const config = {
  // Add more setup options before each test is run
  // 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
export default createJestConfig(config);

❗️config 안에 moduleDirectories: ["node_modules", "<rootDir>/"] 를 추가하자

jest 설치시 주의 사항

  1. Typescript에서 jest에 대한 타입에 대해 오류가 뜬다면
1
yarn add --dev @types/jest"

타입을 한번 더 설치해주자

  1. @testing-library/react 구 버전을 쓸 경우 import 를 인식 못 할 수도 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//❗️ import nextJest from "next/jest.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
/** @type {import('jest').Config} */
const config = {
  // Add more setup options before each test is run
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],

  testEnvironment: "jest-environment-jsdom",
  moduleDirectories: ["node_modules", "<rootDir>/"]
};

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

import nextJest from "next/jest.js";const nextJest = require("next/jest");

export default createJestConfig(config)module.exports = createJestConfig(config);

로 바꿔주면 문제가 해결된다.

Jest 사용 방법

우선 실행환경을 가추기 위해 package.json 에 scripts 부분에 “test": "jest” 를 꼭 추가해주자!

다른 react외의 환경에서는 테스트 하고 싶은 부분에 __**test**__ 폴더를 만들고 해당 폴더 안에 파일이름.test.ts or 파일이름.test.tsx 형식으로 테스트 파일을 만든다.

next에서 폴더안에 만들면 주소의 형식이기 때문에 next에서는 루트 위치에 폴더를 만들어서 한번에 관리와 사용하는것도 하나의 방법이다.

참고 페이지

Optimizing: Testing

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.