Next.js + Typescript에 테스트 환경 구축하기

Minju Kim·2022년 12월 14일
3
post-thumbnail

https://nextjs.org/docs/testing#quickstart-2
현재 회사에서 사용중인 Next.js + TypeScript기반 프로젝트에 테스트 코드를 적용해보고자 한다.

1. Jest, React Testing Library 설치

1-1. jest 설치

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

오류발생
기존에 설치된 모듈 중에 openid-client와 노드 버전이 안맞다는 오류가 있어서 찾아보니, NextAuth.js가 다음버전에서는 노드 버전에 영향받지 않도록 수정될거라는 말이 있었다.

error openid-client@5.1.9: The engine "node" is incompatible with this module. Expected version "^12.19.0 || ^14.15.0 || ^16.13.0". Got "18.6.0"

해결
--ignore -engines 옵션을 사용해 다시 설치해주었다.

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

1-2. eslintrc.json을 사용하고 있기에 추가 설정

//eslintrc.json
{
  "env": {
    // ...
    "jest": true
  }
  // ...
}

2. jest.config.js설정

프로젝트 root에 jest.config.js를 생성하고 아래와 같이 설정해준다.

// 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 = {
  // Add more setup options before each test is run
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
  moduleDirectories: ['node_modules', '<rootDir>/src'],
  testEnvironment: 'jest-environment-jsdom',
  testPathIgnorePatterns: ['<rootDir>/src/next-auth'],
    moduleFileExtensions: ['ts', 'tsx', 'js', 'mjs', 'cjs', 'jsx', 'json', 'node'],
};

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

추가 적용 옵션

2-1. 공식문서에서 moduleDirectoriesmoduleDirectories: ['node_modules', '<rootDir>/']라고 되어있지만 tsconfig.json의 baseUrl 설정을 "./src"로 해줬기에 뒤에 src를 추가해주었다.
https://stackoverflow.com/questions/50171412/jest-typescript-absolute-paths-baseurl-gives-error-cannot-find-module

2-2. 나는 next-auth에 있는 test 코드들을 무시하고 싶어서 testPathIgnorePatterns를 추가 적용해주었다.

2-3. 타입스크립트를 사용하고 있기에 Jest 공식문서의 권장사항에 따라 tstsx를 앞으로 옮겨주었다.

추가로 Next.js 컴파일러가 아래와 같은 설정을 자동적으로 해준다고 한다.

  • Auto mocking of .css, .module.css (and their .scss variants), and image imports
  • Automatically sets up transform using SWC
  • Loading .env (and all variants) into process.env
  • Ignores node_modules from test resolving and transforms
  • Ignoring .next from test resolving
  • Loads next.config.js for flags that enable experimental SWC transforms

내가 세팅한 방법이 Rust Compiler를 사용한 건데 따라서 babel 설정하는 법으로 안해도 되고, 추가로 적용하고 싶은 옵션이 있다면 customJestConfig에 추가해주면 된다는 내용이다.

3. jest.setup.js 설정

TypeScript가 적용된 Next.js 프로젝트에서 Jest로 테스트 코드를 작성하기 위해서는 Jest를 설정할 필요가 있다. 따라서 ./jest.setup.js 파일을 생성하고 아래와 같이 설정해준다.

// Optional: configure or set up a testing framework before each test.
// If you delete this file, remove `setupFilesAfterEnv` from `jest.config.js`

// Used for __tests__/testing-library.js
// Learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect'

4. script 설정

package.json 파일에서 스크립트 설정을 해준다.

"scripts": {
  ...
  "test": "jest --watch",
  "test:ci": "jest --ci"
},

test : watch 모드를 적용하여 파일에 변경사항이 있을때 테스트를 실행하도록 해준다.
test:ci: CI/CD에서 테스트 코드를 실행할 때 사용한다.

5. ts.config 설정

jest.setup.js를 include해준다.

{
...
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "jest.setup.js"],
  "exclude": ["node_modules"]
}

6. 기타

1) 폴더 구조
내가 본 강의에서는 __tests__ 폴더를 만들어 테스트 코드만 별도로 관리하던데, 주변 개발자들에게 물어보니 컴포넌트 단위로 컴포넌트 폴더 하위에 componentName.spec.tsx 파일을 만들어 테스트 코드를 작성하고 있다고 한다. 찾아보니 cra에서도 같은 폴더 안에 test파일 넣는 것을 추천하고 있다. 또한 PR을 올리면 깃헙 액션으로 자동으로 테스트 하도록 설정하고 있다고 한다.

jest는 다음과 같은 suffix를 가진 파일들을 테스트 파일로 인식한다.

__tests__ 파일안의 js 파일들
.test.js 
.spec.js

2) EsLint 추가 설정
Jest로 테스트를 작성하기 위한 몇 가지 권장되는 기본 린트 규칙

no-focused-tests
no-commented-out-tests
valid-expect-in-promise
no-conditional-expect

🥝 참고로, CRA로 만든 프로젝트는 이미 jest와 RTL이 설치되어 있어 별도로 설치해줄 필요가 없다.

참고한 링크

프런트엔드 단위 테스트 모범 사례
Next.js 테스트
Next.js 공식문서 중 Jest and React Testing Library

profile
⚓ A smooth sea never made a skillful mariner

0개의 댓글