14.3
Jest
Jest는 JavaScript 및 TypeScript 애플리케이션을 테스트하기 위한 포괄적인 테스트 프레임워크입니다. Meta(구 Facebook)에서 개발한 Jest는 유닛 테스트, 통합 테스트, 스냅샷 테스트를 지원하며, 설정이 간편하고 다양한 기능과 확장 기능을 통해 강력한 테스트 환경을 제공합니다. 빠른 실행 속도와 훌륭한 디버깅 도구로도 유명합니다. 참고로 Next.js 버전12부터는 Jest에 대한 설정이 기본적으로 내장되어 있습니다.
아래 명령어와 같이 create-next-app을 with-jest 예제와 함께 실행하여 Jest가 설치된 형태의 Next.js 애플리케이션을 곧바로 생성할 수 있습니다.
npx create-next-app@latest --example with-jest with-jest-app
Jest를 수동으로 설치하려면 먼저 다음과 같이 jest와 관련 패키지들을 개발 종속성으로 설치해야 합니다.
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
# or
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
# or
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
패키지 설치 이후 아래 명령을 실행하여 기본 Jest 설정 파일을 생성합니다.
npm init jest@latest
# or
yarn create jest@latest
# or
pnpm create jest@latest
그러면 jest.config.js(또는 jest.config.ts) 파일 자동 생성을 포함하여 프로젝트에 Jest를 설정하기 위한 일련의 프롬프트가 표시됩니다. 과정을 모두 마치면 Jest 설정 파일이 생성되는데, 아래와 같이 next/jest 패키지를 사용하도록 변경해줍니다.
// jest.config.ts
import type { Config } from 'jest';
import nextJest from 'next/jest.js';
const createJestConfig = nextJest({
// 테스트 환경에 사용할 Next.js 애플리케이션 경로
dir: './',
});
// Jest 커스텀 설정
const config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// 각 테스트가 실행되기 전에 필요한 옵션 작성
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
};
// next/jest가 비동기인 Next.js 설정을 로드할 수 있도록 하기 위해, createJestConfig를 아래와 같이 export 해야함
export default createJestConfig(config);
next/jest는 내부적으로 다음과 같은 Jest 설정을 자동으로 구성합니다.
.css, .module.css 및 그들의 SCSS 변형)next/font 자동 모킹.env를 process.env에 로드node_modules 무시.next 무시next.config.js 로드NOTE. 알아두면 좋은 점
환경 변수를 직접 테스트하려면 별도의 설정 스크립트나jest.config.ts파일에서 수동으로 로드하면 됩니다.
마지막으로 package.json 파일에 Jest를 위한 test, test:watch 스크립트를 추가합니다. 참고로 jest --watch는 파일이 변경되면 테스트를 다시 실행하는 명령어입니다.
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest",
"test:watch": "jest --watch"
}
}
Jest를 사용해서 테스트를 작성하고 실행하는 방법에 대해 살펴보겠습니다. 먼저 아래와 같이 간단한 형태의 Page 컴포넌트가 있다고 해보겠습니다.
// app/page.tsx
import Link from 'next/link';
export default function Home() {
return (
<div>
<h1>Home</h1>
<Link href='/about'>About</Link>
</div>
);
}
이 Page 컴포넌트가 제목(<h1> 태그)을 성공적으로 렌더링하는지 확인하기 위한 테스트 코드를 아래와 같이 작성합니다.
// __tests__/page.test.jsx
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import Page from '../app/page';
describe('Page', () => {
it('renders a heading', () => {
render(<Page />);
const heading = screen.getByRole('heading', { level: 1 });
expect(heading).toBeInTheDocument();
});
});
추가로 컴포넌트의 예기치 않은 변경 사항을 추적하기 위해 아래와 같이 스냅샷 테스트를 작성할 수도 있습니다.
// __tests__/snapshot.js
import { render } from '@testing-library/react';
import Page from '../app/page';
it('renders homepage unchanged', () => {
const { container } = render(<Page />);
expect(container).toMatchSnapshot();
});
테스트 코드를 모두 작성한 이후 터미널에서 아래 명령을 실행하여 테스트를 실행하면 됩니다.
npm run test
# or
yarn test
# or
pnpm test
마지막 업데이트: 2025년 10월 24일 04시 12분
이 문서의 저작권은 이인제(소플)에 있습니다. 무단 전재와 무단 복제를 금합니다.
On this page