Front End/React

Vite + React + Typescript + Jest 환경 구성

YJ_SW 2024. 1. 3. 13:26
728x90

Vite + React + Typescript + Jest 환경 구성

vite + React project 생성

npm create vite@latest

jest 를 사용하기 위해 필요한 라이브러리를 설치합니다.

npm i -D jest @types/jest ts-node ts-node ts-jest @testing-library/react identity-obj-proxy jest-environment-jsdom @testing-library/jest-dom jest-svg-transformer

jest 실행을 위해 package.json 에 명령어 추가하기

"scripts":{
    ...
    "test": "jest"
 }

npm run test 실행하면 아래와 같은 결과가 나온다.

Jest 설정파일 추가

루트에 jest.config.ts 파일 생성

/jest.config.ts

export default {
    testEnvironment: 'jsdom',
    transform: {
        '^.+\\\\.tsx?$': 'ts-jest',
    },
    moduleNameMapper: {
        '^.+\\\\.svg$': 'jest-svg-transformer',
        '\\\\.(css|less|sass|scss)$': 'identity-obj-proxy',
    },
    setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
};

루트에 jest.setup.ts 파일 생성

/jest.setup.ts

import '@testing-library/jest-dom';

이때 module에 lint에러가 나온다면 .eslintrc.cjs 파일에 아래 내용을 추가합니다.

.eslintrc.cjs

module.exports = {
  env: {
    ...,
  	module: "node",
  }
}

그래도 에러가 발생한다면 아래 추가

/.eslintignore

.eslintrc.cjs
jest.config.ts
jest.setup.ts

tsconfig.json

tsconfig.json 파일 compilerOptions 내에 다음과 같이 값을 추가합니다.

{
	"compilerOptions":{
      	...,
		"esModuleInterop": true
    }
}

 

/src/__test__/App.test.tsx

import '@testing-library/jest-dom';
import {render} from '@testing-library/react';
import App from '../App';

test('demo', () => {
    expect(true).toBe(true);
});

test('Renders the main page', () => {
    render(<App />);
    expect(true).toBeTruthy();
});

 

 

 

참고 블로그 : https://velog.io/@thdrldud369/Vite-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8%EC%97%90-jest-%EC%B6%94%EA%B0%80%ED%95%98%EA%B8%B0

728x90