이 영역을 누르면 첫 페이지로 이동
Nuhends 의 Tech Life 블로그의 첫 페이지로 이동

Nuhends 의 Tech Life

페이지 맨 위로 올라가기

Nuhends 의 Tech Life

IT / Tech / 재테크 관련 뉴스를 최대한 알기 쉽게 전달하는 Tech 블로그 입니다.

[Next.js] jest로 unit Test 하기

  • 2022.10.31 00:13
  • 프로그래밍/NextJS
반응형

Testing with next.js

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

댓글

이 글 공유하기

  • 구독하기

    구독하기

  • 카카오톡

    카카오톡

  • 라인

    라인

  • 트위터

    트위터

  • Facebook

    Facebook

  • 카카오스토리

    카카오스토리

  • 밴드

    밴드

  • 네이버 블로그

    네이버 블로그

  • Pocket

    Pocket

  • Evernote

    Evernote

다른 글

  • [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
다른 글 더 둘러보기

정보

Nuhends 의 Tech Life 블로그의 첫 페이지로 이동

Nuhends 의 Tech Life

  • Nuhends 의 Tech Life의 첫 페이지로 이동
반응형

검색

메뉴

  • 홈
  • 웹 개발
  • 경제 데이터
  • 경제 공부
  • 방명록

카테고리

  • 분류 전체보기 (127)
    • 프로그래밍 (69)
      • React (3)
      • HTML&CSS 사전 (13)
      • JAVASCRIPT 사전 (11)
      • Algorithm (23)
      • 이슈 정리 (2)
      • 개발 환경 (4)
      • NodeJS (1)
      • Typescript (4)
      • NextJS (5)
      • React-Query (2)
      • ai (1)
    • 경제 데이터 (22)
      • 주식 순위 (20)
      • 경제지표 (2)
    • 경제 공부 (25)
      • 경제 신문 읽기 (3)
      • 세금 재테크 (7)
      • 인사이트 (4)
      • 경제용어정리 (9)
      • 정부 지원 제도 관련 (2)
    • 팁 모음 (11)
      • 인터넷 (5)
      • 생활 (3)
      • SNS 맛집 (3)

최근 글

인기 글

댓글

공지사항

아카이브

태그

  • 코딩테스트
  • 알고리즘
  • 코테 풀이
  • softeer
  • 코테
  • 프로그래머스
  • 자바스크립트
  • javascript

나의 외부 링크

정보

nuhends의 Nuhends 의 Tech Life

Nuhends 의 Tech Life

nuhends

블로그 구독하기

  • 구독하기
  • RSS 피드

방문자

  • 전체 방문자
  • 오늘
  • 어제

티스토리

  • 티스토리 홈
  • 이 블로그 관리하기
  • 글쓰기
Powered by Tistory / Kakao. © nuhends. Designed by Fraccino.

티스토리툴바