[yarn berry + Next.js + TypeScript] React Testing Library 적용하기
create next app
yarn create next-app ${project name} --typescript
TypeScript 기반으로 next.js 애플리케이션을 생성한다.
yarn 버전 변경
아래 글을 참고해주시면 감사하겠습니다.
(yarn berry 미 사용시 skip 하셔도 됩니다.)
https://kimyanglogging.tistory.com/8
[Next.js] yarn berry 적용 방법 (with vscode setting)
yarn berry? (yarn 2) 기존 node_modules의 문제점을 개선하기 위해 출시된 yarn의 상위 버전이다. next.js 애플리케이션 생성 yarn create next-app ${project name} yarn version 확인 생성한 애플리케이션으로 이동하여
kimyanglogging.tistory.com
Test 관련 dependency 설치
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
js의 예제로 구성된 공식 문서에는 위 커멘드만 나와있지만, typescript와 사용하기 위해서는 아래의 커멘드를 추가로 입력해야한다.
yarn add -D @types/jest @types/testing-library__jest-dom
나 같은 경우는 jest 실행 시, ts-node 관련 issue가 발생하여 아래 커멘드로 입력해주었다.
yarn add -D ts-jest
jest 관련 설정
project 최상위 (package.json과 같은 위치)에 아래 파일들을 생성한다.
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
/** @type {import('jest').Config} */
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
moduleDirectories: ['.yarn', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
}
export default createJestConfig(customJestConfig)
jest.setup.ts
import '@testing-library/jest-dom/extend-expect'
작동 확인
테스트 파일 (ex. "*.test.tsx")을 작성 후 jest 커맨드 (ex. yarn jest --watch --coverage)를 입력하면 정상적으로 동작한다.
Ref.
https://nextjs.org/docs/testing#setting-up-jest-with-the-rust-compiler
Testing | Next.js
Learn how to set up Next.js with three commonly used testing tools — Cypress, Playwright, Jest, and React Testing Library.
nextjs.org
https://github.com/vercel/next.js/tree/canary/examples/with-jest
GitHub - vercel/next.js: The React Framework
The React Framework. Contribute to vercel/next.js development by creating an account on GitHub.
github.com