티스토리 뷰

cra로 프로젝트 생성

> yarn create react-app cra_ts_jest --template typescript

 

CRA 환경에서는 Test Runner로 Jest를 사용하고 있기 때문에

Jest를 따로 설치하지 않아도 yarn test를 통해 테스트코드를 실행할 수 있다.

(프로젝트 생성 직후 yarn test 명령을 하면  App.test.tsx  테스트코드가 실행되는 것을 확인할 수 있다.) 

 

> yarn test

PASS가 나온다면 완료. 

 

 

실행 중 ' TypeError: expect(...).toBeInTheDocument is not a function '와 같은 에러가 발생한다면,  아래와 같이 설정. 

// src/setuptests.ts

import '@testing-library/jest-dom';
//jest.config.js
module.export = {
	..., 
    setupFilesAfterEnv: ["<rootDir>/src/setupTests.ts"],	//프로젝트 설정 시 생성되어있던 jest선언 파일을 호출(경로변경 가능)
}

특별한 설정을 하지 않은 기본 프로젝트라면 이정도에서 test 실행이 가능할 것. 

sample code : https://github.com/wmi1105/CRA_Typescript_Jest_Template

 


tsconfig를 통해 import 경로를 지정해서 사용하는 경우가 있다. 

' import * from @src/SamplePage.tsx '와 같이 호출하려 한다면 

 

 Craco를 설치하고 설정을 통해 @src 경로를 지정해 주어야 한다.

> yarn add @craco/craco craco-alias
> yarn add -D ts-jest

Craco(Create-React-App Configuration Override) :  

cra의 config 설정을 덮어쓰기 위한 패키지

 

craco 패키지를 설치하고 아래 설정 파일들을 root 경로에 추가

//craco.config.js

const CracoAlias = require("craco-alias");
module.exports = {
  plugins: [
    {
      plugin: CracoAlias,
      options: {
        source: "tsconfig",
        tsConfigPath: "tsconfig.paths.json",
      },
    },
  ],
};
//tsconfig.path.json
{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@src/*": ["src/*"]
    }
  }
}
//tsconfig.json
{
  "extends": "./tsconfig.paths.json",
  ...
}
//jest.config.js

module.exports = {
	..., 
  moduleNameMapper: {
    "^@src/(.*)$": "<rootDir>/src/$1", //경로의 이름과 실제 경로 설정
  }
};
// package.json

{
	...
    "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "jest --env=jsdom",
    "eject": "craco eject"
  },
}

sample code : https://github.com/wmi1105/end_talk_game/tree/master/client 

 


** 추가

test실행 시 import .svg 오류 

import한 파일이 어떤 형식인지 알수 없어서 라고 한다

> yarn add -D jest-svg-transformer
// jest.config.js
module.exports = 
{
    ..., 
    moduleNameMapper: {
    ...,
    "^.+\\.(css|less|scss|otf)$": "babel-jest",
    "^.+\\.svg$": "jest-svg-transformer",
  },
}

 

ProjectTemplate.zip
0.19MB


참고 

- https://velog.io/@jiseong/test-jest%EC%99%80-react-testing-library-%EA%B3%B5%EB%B6%80

- https://runebook.dev/ko/docs/jest/expect#expectnotarraycontainingarray 

- https://dkrnfls.tistory.com/221

- https://all-dev-kang.tistory.com/entry/%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-jest-import-svg-%ED%95%A0%EB%95%8C-%EC%83%9D%EA%B8%B0%EB%8A%94-%EB%AC%B8%EC%A0%9C%EC%A0%90%EC%97%90-%EB%8C%80%ED%95%98%EC%97%AC 

 

 

expect option명세 :  https://www.js2uix.com/frontend/jest-study-step3/

'SW프로그래밍 > FrontEnd 개발환경' 카테고리의 다른 글

Plugin  (0) 2022.01.18
Loader  (0) 2022.01.17
Webpack  (0) 2022.01.13
Module  (0) 2022.01.13
NPM  (0) 2022.01.13
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함