[Next] 테스트 환경 구축하기

Gyuhan Park·2023년 7월 1일
0

nextjs

목록 보기
10/10

📖 테스팅 라이브러리란?

jest : JS test runner. jest를 통해 테스트 코드를 돌리고 RTL 함수를 가져와 테스트 코드를 작성한다.
RTL : React Testing Library

  • Behavior Driven Test(행위 주도 테스트) 방법론
  • jsdom이라는 라이브러리를 통해 실제 브라우저 DOM을 기준으로 테스트 작성
  • 사용자 브라우저에서 랜더링하는 실제 HTML 마크업의 모습이 어떤지에 대해서 테스트하기 용이
  • 사용자 브라우저에서 랜더링하는 실제 HTML 마크업의 모습이 어떤지에 대해서 테스트하기 용이

Enzyme : airbnb에서 만든 테스팅 라이브러리

  • Implementation Driven Test 방법론
  • React가 만들어내는 가상 DOM을 기준으로 테스트 작성
  • 테스트 대상 React 컴포넌트에 어떤 prop이 넘어가고, 현재 state이 어떻게 되는지에 대해서 검증하기 용이

Jest와 RTL을 이용하여 테스트 코드를 작성하기 위한 환경을 구축해보려 한다

🛠️ Next + TS 테스트 환경 구축

dependency 설치

jest와 React-Testing-Library, typescript 관련 라이브러리를 설치한다.

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

jest.config.js

nest에서 jest를 사용할 수 있도록 jest.config.js 파일을 생성하였다.
node_modules 폴더가 존재한다면 moduleDirectories를 설정해줘야 한다.

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",
  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);

jest.setup.js

jest.config.js 에서 설정한 setupFilesAfterEnv 에 따라 파일 생성.
각 테스트가 실행되기 전에 추가적으로 옵션을 설정할 수 있다.

// Learn more: https://github.com/testing-library/jest-dom
import "@testing-library/jest-dom/extend-expect";

package.json

test 코드를 실행할 script를 추가한다.

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

tsconfig.json

include에 jest.setup.js 를 추가해준다.

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

💻 테스트 코드

Home 컴포넌트에 대해 간단히 테스트 코드를 작성해보았다.

// Home.tsx
export default function Home() {
  ...
  return (
    ...
	<h1>One Step</h1>
    ...
    )
}

jest 함수가 호출이 안됐는데 @types/jest 를 설치하면 import하지 않아도 된다.

// Home.spec.tsx
import { render } from "@testing-library/react";
import Home from ".";

describe("contentList test", () => {
  it("renders content", () => {
    const { getByText } = render(<Home />);
    const mainTitle = getByText("One Step");
    expect(mainTitle).toBeInTheDocument();
  });
});

😎 테스트 결과

yarn test 스크립트를 실행해보면 결과가 나온다.
테스트 실행 시간도 나오는데 API 호출하는 테스트를 진행하여 호출 시간을 줄여보는 경험도 하고싶다.

jest 공식 홈페이지
React-Testing-Library
next.js 공식 홈페이지
Next+TS 환경에서 테스트 환경 구축

profile
단단한 프론트엔드 개발자가 되고 싶은

0개의 댓글