백견이불여일타(百見而不如一作)
Jest is a delightful JavaScript Testing Framework with a focus on simplicity.
단순성에 초점을 맞춘 즐거운 JavaScript 테스트 프레임워크입니다.
Nextjs 한글 문서 (커뮤니티) → Jest
https://nextjs-ko.org/docs/app/building-your-application/testing/jest
npm i jest
기본파일 생성
npm init jest@latest
# 또는
yarn create jest@latest
# 또는
pnpm create jest@latest
jest.config.ts 파일 생성
import type { Config } from 'jest'
import nextJest from 'next/jest.js'
const createJestConfig = nextJest({
// next.config.js 및 .env 파일을 테스트 환경에 로드하기 위해 Next.js 앱 경로를 제공합니다.
dir: './',
})
// Jest에 전달할 사용자 정의 구성을 추가합니다.
const config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// 각 테스트가 실행되기 전에 추가 설정 옵션을 추가합니다.
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
// next/jest가 Next.js 구성을 로드할 수 있도록 createJestConfig가 이 방식으로 내보내집니다.
export default createJestConfig(config)
jest.config.js(ts가 아니라면)
const nextJest = require('next/jest')
/** @type {import('jest').Config} */
const createJestConfig = nextJest({
// next.config.js 및 .env 파일을 테스트 환경에 로드하기 위해 Next.js 앱 경로를 제공합니다.
dir: './',
})
// Jest에 전달할 사용자 정의 구성을 추가합니다.
const config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// 각 테스트가 실행되기 전에 추가 설정 옵션을 추가합니다.
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
// next/jest가 Next.js 구성을 로드할 수 있도록 createJestConfig가 이 방식으로 내보내집니다.
module.exports = createJestConfig(config)
유용한 정보__: 환경 변수를 직접 테스트하려면 별도의 설정 스크립트나 jest.config.ts 파일에서 수동으로 로드해야 합니다. 자세한 내용은 테스트 환경 변수를 참조하세요.
프로젝트에서 Module Path Aliases를 사용하는 경우, jsconfig.json 파일의 경로
옵션과 jest.config.js 파일의 moduleNameMapper 옵션을 일치시켜 Jest가 가져오기를 해결하도록
구성해야 합니다.
tsconfig.json or jsconfig.json
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"baseUrl": "./",
"paths": {
"@/components/*": ["components/*"]
}
}
}
@testing-library/jest-dom은 .toBeInTheDocument()와 같은 편리한
커스텀 매처(opens in a new tab)를 포함하여 테스트 작성을 더 쉽게 만듭니다.
다음 옵션을 Jest 구성 파일에 추가하여 모든 테스트에서 커스텀 매처를 가져올 수 있습니다.
jest.config.ts
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
그런 다음 jest.setup.ts 파일에 다음 import를 추가하세요:
jest.setup.ts
import '@testing-library/jest-dom'
유용한 정보__: extend-expect는 v6.0에서 제거되었습니다(opens in a new tab), 따라서 버전 6 이전의 @testing-library/jest-dom을 사용하는 경우 @testing-library/jest-dom/extend-expect를 대신 가져와야 합니다.
각 테스트 전에 더 많은 설정 옵션이 필요하면 위의 jest.setup.js 파일에 추가할 수 있습니다.
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest",
"test:watch": "jest --watch"
}
}
jest --watch는 파일이 변경될 때 테스트를 다시 실행합니다.
더 많은 Jest CLI 옵션에 대해서는 Jest Docs(opens in a new tab)를 참조하세요.
프로젝트의 루트 디렉토리에 tests 폴더를 생성하세요.
예를 들어,
import Link from 'next/link'
export default function Home() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}
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
# 또는
yarn test
# 또는
pnpm test
위에 내용은 공식문서에 나와있는 내용이며 해당 내용을 했을때 에러
Error: Jest: 'ts-node' is required for the TypeScript configuration files. Make sure it is installed
해결방법
npm i ts-node