Front-end/Next.js

[Next.js] React+Nest의 테스트(Jest & Test-Library)

Bay Im 2024. 3. 8. 00:31
  • Test in Next.js
    • cmd 창 프로젝트 최상단 디렉터리 위치에서 npm i -D @testing-library/jest-dom@5.16.5 @testing-library/react @testing-library/user-event jest jest-environment-jsdom ts-jest ts-node 입력
    • package.json scripts 블록에 아래 코드 추가
    • "test": "jest",
      "test:watch": "jest --watchAll"
    • cmd 창 프로젝트 최상단 디렉터리 위치에서 npm init jest@latest 입력
    • jest.config.ts에 아래 코드 추가
    • // setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
        moduleNameMapper: {
          '@/app/(.*)$': '<rootDir>/app/$1',
          '@/lib/(.*)$': '<rootDir>/lib/$1',
          '@/components/(.*)$': '<rootDir>/components/$1',
        },
     
  • Test 작성
    • tsconfig.json 파일을 복사, 붙여넣기 하여 tsconfig.spec.json 으로 이름 변경
      • tsconfig.spec.json 파일에서 "jsx": "react-jsx", 으로 변경
    • jest.config.ts 파일에서 transform: 아래에 아래 코드 추가
    • transform: {
          '^.+\\.[tj]sx?$': [
            'ts-jest',
            {
              tsconfig: '<rootDir>/tsconfig.spec.json',
            },
          ],
        },
    • 프로젝트 최상단 디렉터리에 test 폴더 생성
      • Home.test.tsx 파일 생성
      • About.test.tsx 파일 생성

 

728x90