Notice
Recent Posts
Recent Comments
Link
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Tags
more
Archives
Today
Total
관리 메뉴

juni

Jest / Vitest 본문

CS

Jest / Vitest

juni_shin 2024. 10. 11. 20:05

Jest / vitest 기반 유닛 테스트 코드 작성 및 테스트

참고 사이트

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

 

Vite 프로젝트에 Jest 추가하기

Vite로 만들어진 React 프로젝트에 Jest를 추가하는 방법에 대한 설명

velog.io

 

하지만 jset를 사용하려는데 에러가 발생했습니다.

Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\sangj\OneDrive\바탕 화면\sparta\onboarding\node_modules\strip-ansi\index.js from C:\Users\sangj\OneDrive\바탕 화면\sparta\onboarding\node_modules\string-width\index.js not supported.
Instead change the require of C:\Users\sangj\OneDrive\바탕 화면\sparta\onboarding\node_modules\strip-ansi\index.js in C:\Users\sangj\OneDrive\바탕 화면\sparta\onboarding\node_modules\string-width\index.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (C:\Users\sangj\OneDrive\바탕 화면\sparta\onboarding\node_modules\string-width\index.js:2:19)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

 

현재 문제는 **require()**로 ES 모듈을 불러오려는 시도에서 발생하는 것입니다. Jest는 기본적으로 CommonJS를 사용하며, ES 모듈을 사용하는 패키지를 불러올 때 문제가 발생합니다. 이 문제는 주로 string-width 및 strip-ansi와 같은 패키지에서 발생합니다.

문제 분석:

  • strip-ansi 및 string-width 라이브러리가 ESM (ECMAScript Module) 형식으로 작성되었고, Jest가 이를 require() 방식으로 불러오면서 충돌이 발생하고 있습니다.
  • ERR_REQUIRE_ESM 에러는 Jest가 ES 모듈을 지원하지 않는 방식으로 불러오려고 할 때 발생합니다.

 

오류를 해결하려 하였으나 해결 실패로 vitest를 적용하였습니다.

 

Vitest 설치

yarn add -D vitest

 

Vite 설정 파일(vite.config.ts)에서 test 옵션을 추가합니다

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: "jsdom",
  },
})

 

그 후 yarn vitest 명령어로 테스트를 실행할 수 있습니다.

 

하지만, test에서

이 호출과 일치하는 오버로드가 없습니다.
  마지막 오버로드에서 다음 오류가 발생했습니다.
    개체 리터럴은 알려진 속성만 지정할 수 있으며 'UserConfigExport' 형식에 'test'이(가) 없습니다.ts(2769)
index.d.ts(3194, 18): 여기서 마지막 오버로드가 선언됩니다.
⚠ Error(TS2769)  | 
이 호출과 일치하는 오버로드가 없습니다.
   

마지막 오버로드에서 다음 오류가 발생했습니다.
          	개체 리터럴은 알려진 속성만 지정할 수 있으며 UserConfigExport 형식에 test 이(가) 없습니다.
(property) test: {
    globals: boolean;
    environment: string;
}

이런 문제를 확인 ( test 실행에는 문제가 없었습니다. ) 하였습니다.

 

Vitest의 타입 정의 추가

TypeScript 환경에서 Vitest를 사용하려면 Vitest의 타입 정의도 추가로 설치해야 합니다. 이 패키지를 설치하지 않으면 TypeScript는 Vite 설정에 test 속성을 인식하지 못할 수 있습니다.

yarn add -D @vitest/coverage-c8 @vitest/ui @vitest/browser vitest

 

TypeScript 설정에 Vitest 추가

TypeScript 설정 파일(tsconfig.json)에 Vitest 환경을 추가해야 합니다. 이 설정이 없으면 TypeScript는 **test**와 관련된 Vitest 속성을 인식하지 못합니다.

tsconfig.json에 다음을 추가하세요

{
  "compilerOptions": {
    // ... (다른 옵션)
    "types": ["vitest/globals"], // Vitest 타입 추가
    "moduleResolution": "node"   // Node.js 환경에 맞게 모듈 해석
  }
}

 

Vite 설정의 타입 선언 확인

Vite 설정 파일에서 test 속성에 대한 타입을 확실하게 인식시키기 위해 Vitest 타입을 Vite 설정에 명시적으로 추가해야 할 수 있습니다. Vite 설정 파일에 Vitest 관련 타입을 명시적으로 가져오세요.

/// <reference types="vitest" />

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from 'tailwindcss';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  css: {
    postcss: {
      plugins: [tailwindcss()],
    },
  },
  test: {
    globals: true,         // 글로벌 테스트 환경 사용
    environment: 'jsdom',  // 브라우저 환경에서 테스트 실행
  },
});

 

마지막으로 reference types까지 작성하여 해결하였습니다.

 

test 코드

import { sum } from "./sum";

test("1 + 2는 3이 되어야 한다.", () => {
  expect(sum(1, 2)).toBe(3);
});

test("3 + 5는 8이 되어야 한다.", () => {
  expect(sum(3, 5)).toBe(8);
});

 

실행 코드

export const sum = (a: number, b: number): number => {
  return a + b;
};

 

결과