Next.js에서 단위 테스트를 하기 위해서 공식 문서에서 설명하는 Jest와 React Testing Library를 사용했다.

 

먼저 4개의 라이브러리를 설치한다. 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

 

루트 경로에 jest.config.mjs 파일을 생성하여 아래와 같이 내용을 추가해준다.

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 config = {
  // Add more setup options before each test is run
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
 
  testEnvironment: 'jest-environment-jsdom',
}
 
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)

Next.js에서 SWC 컴파일러를 사용하기 때문에 더 이상 설정은 필요 없다.

 

버튼 컴포넌트의 테스트 코드를 작성해봤다.

import { render } from '@testing-library/react';

import Button from './index';

it('button component snapshot', () => {
    const buttonRender = render(
        <Button type="button" onClick={() => console.log('button onClick')}>
            Test Button
        </Button>
    );

    expect(buttonRender.container).toMatchSnapshot();
});

테스트 코드도 잘 통과 됐고 아래와 같이 스냅샷도 생성이 됐다.

 

마지막으로 package.json에서 test 스크립트를 추가 했다.

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "test": "jest --watch"
  }
}

 

웹스톰에서는 동작에는 문제 없지만 코드에 문제 있다는 경고를 표시했다. @types/jest를 설치해주니 말끔하게 해결했다.

npm i --save-dev @types/jest

 

반응형

+ Recent posts