[Next.js] jest로 unit Test 하기
반응형
1. jest란?
💡 Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!
출처: jest 공식 홈페이지
코드가 제대로 동작하는지 확인하는 Test case를 만드는 JS Testing Framework(페이스북이 개발)이다.
2. Setting up jest (with Rust Compiler)
Next.js 12 버전부터 Next 내부에 Jest를 위한 설정이 built-in 되어 있다.
1. 패키지 설치
Jest를 셋업 하기 위해 jest, jest-environment-jsdom, @testing-library/react, @testing-library/jest-dom 패키지를 설치하자.
npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
2. jest.config.js 작성
root 디렉토리에 jest.config.js를 생성하고 아래처럼 작성하자.
// jest.config.js
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
/** @type {import('jest').Config} */
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>/'],
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는 자동으로 Jest에 환경을 적용시켜준다. 상세 내용은 아래와 같다.
- Setting up transform using SWC
- Auto mocking stylesheets (.css, .module.css, and their scss variants) and image imports
- Loading .env (and all variants) into process.env
- Ignoring node_modules from test resolving and transforms
- Ignoring .next from test resolving
- Loading next.config.js for flags that enable SWC transforms
💡 Note: 환경 변수를 바로 테스트 하고 싶다면, 분리된 setup 스크립트 혹은 jest.config.js에서 각각 환경 변수 로드해야 한다. 이번 테스트에서는 환경변수를 사용하지 않는다. 더 정보가 필요하다면 Test Environment Variables 를 참고.
3. 테스트 코드 작성
1. package.json에 script 추가
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest --watch"
}
jest --watch는 file이 변경될 때마다 테스트를 다시 시작시킨다. 더 많은 Jest CLI 옵션에 대해 알고 싶다면 Jest Docs 를 참고.
2. test 파일 추가
src/test 폴더에 test 파일을 추가해보자. (폴더의 위치는 각자 상황에 맞게 정하면 된다)
// src/__tests__/index.test.jsx
import { render, screen } from '@testing-library/react'
import Home from '../pages/index'
import '@testing-library/jest-dom'
describe('Home', () => {
it('renders a heading', () => {
render(<Home />)
const heading = screen.getByRole('heading', {
name: /welcome to next\\.js!/i,
})
expect(heading).toBeInTheDocument()
})
})
4. 테스트 실행
아까 package.json > script에 등록해둔 npm run test를 실행하면 된다. 그러면 test 파일에 적어둔 케이스를 실행해준다.
반응형
반응형
'프로그래밍 > NextJS' 카테고리의 다른 글
[Next.js] 번역-Rendering Fundamentals (0) | 2023.04.09 |
---|---|
[Next.js] 딥링크, Next/Link에서 이슈 (0) | 2022.10.31 |
[Emotion] CSS 속성 사용시 타입 에러 해결 방법(with Next.js) (0) | 2022.09.07 |
[Emotion] emotion(with next v12) 세팅 방법 (1) | 2022.09.07 |
댓글
이 글 공유하기
다른 글
-
[Next.js] 번역-Rendering Fundamentals
[Next.js] 번역-Rendering Fundamentals
2023.04.09 -
[Next.js] 딥링크, Next/Link에서 이슈
[Next.js] 딥링크, Next/Link에서 이슈
2022.10.31 -
[Emotion] CSS 속성 사용시 타입 에러 해결 방법(with Next.js)
[Emotion] CSS 속성 사용시 타입 에러 해결 방법(with Next.js)
2022.09.07 -
[Emotion] emotion(with next v12) 세팅 방법
[Emotion] emotion(with next v12) 세팅 방법
2022.09.07