FrontEnd

[NextJS] JEST로 NextJS 테스트 코드 작성하기

kangminhyuk1111 2024. 1. 5. 10:52
반응형
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는 단순성에 중점을 둔 유쾌한 자바스크립트 테스트 프레임워크입니다.
Babel, TypeScript, Node, React, Angular, Vue 등을 사용하는 프로젝트와 함께 작동합니다

 

- 자바스크립트 테스트 프레임워크이며, 다양한 라이브러리에서 사용이 가능한 프레임워크입니다.

 

1. 패키지 설치

생성되어 있는 NextJS 프로젝트 내부에 생성할 것입니다.

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. config 파일 작성

jest를 이용하려면 각종 config파일의 수정이 필요합니다.

3가지 파일의 생성 및 수정이 필요하다.

2-1. jest.setup.js

//jest.setup.js
import '@testing-library/jest-dom/extend-expect';

// 위에거 안되면 이거 사용해보세요
// import '@testing-library/jest-dom';​

 

 

테스팅 라이브러리 jest확장을 이용하기 위해 추가된 파일

2-2. jest.config.js

const nextJest = require("next/jest");

const createJestConfig = nextJest({
    dir: "./",
});

const customJestConfig = {
    rootDir: ".",
    setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
    moduleNameMapper: {
        "^@/app/(.*)$": "<rootDir>/app/$1",
        "^@/pages/(.*)$": "<rootDir>/pages/$1",
    },
    moduleDirectories: ["node_modules", "<rootDir>/"],
    testEnvironment: "jsdom",
};

module.exports = createJestConfig(customJestConfig);

 

보통 nextjs에서 컴포넌트를 import할때 @/app/~~~ 방식으로 import를 하는데 그렇게 하면 jest 에러가난다.

이유는 jest 에서 테스트 코드 실행시 @/app~ 경로가 해석이 안되기 때문이다.

보통 절대경로로 많이 적기 때문에 이를 정리해주는 jest 설정 파일이다 라고 생각하면 된다.

3. package.json

"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest"
  },​

package.json에 아래 test : jest 까지 추가해주면 정상적으로 가동이 가능하다.

4. 예제

import type { NextPage } from 'next';

const Home: NextPage = () => <div>Home</div>;

export default Home;

해당 페이지를 랜더링 테스트를 하려면 어떻게 하면 될까?

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

import Home from '@/pages/index';

describe('<Home />', () => {
  it('renders a heading', () => {
    const { container } = render(<Home />);

    const home = screen.getByText('Home');

    expect(home).toBeInTheDocument();
    expect(container).toMatchSnapshot();
  });
});

아래와 같이 테스트 파일을 만들어 테스트 코드를 실행하면 된다.

npm test 명령어로 실행하며, 테스트 파일은 반드시 파일명.test.tsx 이런식으로 중간에 반드시 test가 들어가야 한다.

테스트 컴포넌트들은 일반적으로 __test__ 폴더를 생성하여 관리한다.

반응형