Nest.js에 Jest와 React Testing Library를 설정해보자
미뤄왔던 시간이 도래했다.
프로젝트를 시작하면서 애써 외면해왔지만, 여러가지 과정들을 거치면서 결국 테스트의 필요성을 절실히 느끼고 말았다.
그래서 오늘은 Next.js에 Jest와 React Testing Library를 설정해보려고 한다.
Jest & React Testing Library
Jest는 JavaScript로 만들어진 테스팅 프레임워크다.
테스트 파일을 작성하면 이를 찾고, 테스트를 실행하고, 그 결과를 보여주는 역할을 한다.
React Testing Library는 Jest에서 React 컴포넌트를 테스트하도록 도와주는 라이브러리다.
더불어 사용자가 하는 것과 동일한 방식으로 DOM을 쿼리하도록 도와주고 또, DOM과 상호작용하는 방법을 제공한다.
이를 통해 컴포넌트가 실제로 렌더링하는 것에 가깝게 테스트할 수 있게 된다.
설치하기
yarn add --dev jest jest-environment-jsdom ts-node ts-jest @types/jest @testing-library/react @testing-library/jest-dom @testing-library/user-event eslint-plugin-jest eslint-plugin-jest-dom eslint-plugin-testing-library
위 명령어를 이용해 필요한 패키지를 설치한다.
뭐가 좀 많은데 설치되는 패키지는 다음과 같다.
Jest 관련
- jest : JS 테스팅 프레임워크
- jest-environment-jsdom : jest에 가상 DOM을 제공 (v28 이후 버전부터 jsdom을 기본적으로 제공하지 않아 별도 설치 필요)
- ts-node : node 환경에서 TS를 컴파일할 수 있도록 만듬. jest 설정파일을 .ts 파일로 작성하기 위함
- ts-jest : jest가 TS를 이해하고 실행할 수 있도록 도와줌
- @types/jest : TS 환경에서 jest를 사용할 경우 필요한 타입 정의 제공
React Testing Library 관련
- @testing-library/react : Jest를 사용하여 React를 테스트하기 위한 도구
- @testing-library/jest-dom : DOM 환경에 맞는 다양한 Matcher 제공
- @testing-library/user-event : 기본 내장 함수인 fireEvent보다 더 현실적인 Event 발생시키는 도구
ESLint 플러그인
- eslint-plugin-jest : jest 관련 eslint 플러그인
- eslint-plugin-jest-dom : jest dom 관련 eslint 플러그인
- eslint-plugin-testing-library : testing library 관련 eslint 플러그인
ESLint 플러그인은 eslint-plugin-jest-dom과 eslint-plugin-testing-library를 같이 설치해도 되네 마네 말이 좀 있는데
나는 공식문서를 봐도 겹치는 규칙이 없는 것 같아서 나중에 불필요해지면 지우려고 일단 설치했다.
위에는 없지만 testing-library-selector라는 것도 있던데,
테스트 작성 시 동일한 UI를 반복적으로 가져오는 경우에 이를 재사용할 수 있게 만드는 패키지로 보인다.
이는 나중에 필요해지면 설치하려고 한다.
Jest 설정하기
그 다음 Next 공식 문서에 나온대로 jest 설정 파일(jest.config.ts)을 정의해준다.
//jest.config.ts
import nextJest from "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.ts"],
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);
위에서 Next 설정과 다른게 한가지 있는데 jest.setup.ts파일을 따로 만들어줬다는 점이다.
이 파일은 테스트가 실행되기 전에 실행되는 파일로, 테스트 전체적으로 공통되는 기본 환경 설정을 할 수 있는 파일이다.
//jest.setup.ts
import '@testing-library/jest-dom/extend-expect';
//or
import "@testing-library/jest-dom";
jest.setup.ts 파일에 jest-dom을 import하는 코드를 작성했다.
이는 Jest의 expect 함수에 DOM 관련 Matcher를 추가해준다.
(나의 경우 위 코드로는 DOM Matcher가 추가되지 않아 아래 코드를 사용했다.)
//sample.test.ts
test('My First Test', () => {
expect(null).toBeInTheDocument(); // toBeInTheDocument가 자동완성에 뜨는지 체크한다.
})
이후 .test.ts 파일을 하나 작성하여 expect 함수에 DOM 관련 Matcher가 추가되었는지 체크해준다.
package.json에 명령어 추가하기
테스트를 CLI를 통해서 실행하기 위해서 package.json의 scripts에 명령어를 추가해준다.
"scripts": {
...
"test": "jest --watchAll"
},
이제 터미널에서 다음 명령어를 입력하여 jest가 정상적으로 동작하는지 확인한다.
yarn test
ESLint 설정하기
ESLint 플러그인은 'not.toBeDisabled() 라고 작성하는게 아니라 toBeEnabled()라고 작성하세요.' 와 같이
테스트 작성 시 권고되는 작성 방향을 제시해준다.
각 패키지가 어떤 규칙을 가지고 있는지는 패키지의 문서를 참고하자.
설치는 아까 해주었으므로. eslintrc.json 파일을 수정하여 설정해준다.
//.eslintrc.json
{
...
"overrides": [ // 이름에 .test나 .spec이 포함된 파일들에만 플러그인 적용
{
"files": ["**/?(*.)+(spec|test).[jt]s?(x)"],
"plugins": ["jest", "jest-dom", "testing-library"],
"extends": ["plugin:jest/recommended", "plugin:jest-dom/recommended", "plugin:testing-library/react"]
}
],
...
}
overrides를 통해 설정해주었는데 이를 통해 .spec이나 .test가 이름에 들어간 파일에만
test 관련 플러그인이 작동하도록 적용해주었다.
//sample.test.ts
import { screen } from "@testing-library/react";
// expect가 없다고 에러
test("eslint-plugin-jest 테스트: expect-expect", () => {});
test("eslint-plugin-jest-dom 테스트: prefer-enabled-disabled", () => {
const element = document.createElement("div");
//toBeDisabled 쓰라고 에러
expect(element).not.toBeEnabled();
});
test("eslint-plugin-testling-library 테스트: await-async-queries", () => {
//async-await 쓰라고 에러
const button = screen.findByRole("button");
expect(button).toBeEnabled();
});
이후에 린트가 잘 작동하는지 sample.test.ts 파일을 만들어 테스트해준다.
만약 잘 작동하고 있다면 아래와 같이 나올 것이다.
이제 테스트 파일을 작성하면서 Test를 진행하면 된다. 🤗
Reference
밑바닥부터 React 개발 환경 구축하기 - 4. Jest와 Testing-Library
이 글에서는 밑바닥부터 개발 환경 구축하기 3편에 이어서 Jest와 react-testing-library를 사용해서 테스트 환경을 구축하는 과정을 정리합니다. 시리즈 밑바닥부터 React 개발 환경 구축하기 - 1. Webpack
leo-xee.github.io
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
Jest
By ensuring your tests have unique global state, Jest can reliably run tests in parallel. To make things quick, Jest runs previously failed tests first and re-organizes runs based on how long test files take.
jestjs.io
React Testing Library | Testing Library
React Testing Library builds on top of DOM Testing Library by adding
testing-library.com
'Frontend > NextJS' 카테고리의 다른 글
Next.js + Tailwind + Storybook 개발 환경 구축하기 (0) | 2023.07.30 |
---|