TypeScript_JEST TypeScript로 Node TestCast만들기 : npm 프로젝트 생성 및 샘플 테스팅 -1

 JEST는 FaceBook에서 개발한 JavaScript 테스팅 툴입니다. 이는 TypeScript에도 적용이 가능하며 이번 시리즈로 설명하도록 하겠습니다.


JEST공식문서 : https://jestjs.io/docs/getting-started


프로젝트를 만들겠습니다.

1. npm 프로젝트 생성하기

- 해당폴더에 npm 프로젝트를 자동 생성합니다. package.json파일 생성

$ npm init --y




이제 테스팅이 필요한 devDependencies를 설치하겠습니다. 타입스크립트를 작성하기 위해서 필요합니다.

- 개발용으로만 사용할 npm 모듈을 설치합니다 : typescript,ts-node,@types/node

$ npm install -D typescript ts-node @types/node




이제 실제 테스트에 필요한 JEST 모듈을 설치하겠습니다.

- 개발용으로만 사용할 npm 모듈을 설치합니다 : jest, ts-jest, @types/jest

$ npm install -D jest ts-jest @types/jest


{
"name": "testtutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/jest": "^29.0.0",
"@types/node": "^18.7.14",
"install": "^0.13.0",
"jest": "^28.1.3",
"npm": "^8.18.0",
"ts-jest": "^28.0.8",
"ts-node": "^10.9.1",
"typescript": "^4.8.2"
}
}


위 코드에서 test라는 키값을 "jest"로 변경해서 JEST로 테스트 가능하도록 합니다.




이제 각각 app, test폴더를 만들고 Main.ts과 Main.test.ts을 만들어줍니다. Main.test.ts은 Main.ts을 테스트 하기 위한 코드 입니다. 물론 Main.spec.ts으로 할수 있지만 지금을 이렇게 하겠습니다.


// src/test/Main.test.ts
describe('Main test suite', () => {
test('first test', () => {
console.log('test work!!!')
});
})


이제 테스트를 해보겠습니다.

- 전체 JEST테스트

$ npm test




// src/app/Main.ts
export class Fun{
public static toUpperC(arg : string){
return ""
}
}


// src/test/Main.test.ts
import {Fun} from '../app/Main'

describe('Main test suite', () => {
test('first test', () => {
console.log('test work!!!')
const str = Fun.toUpperC('str');
});
})


그럼 실제 구동되는 코드를 구현하기 위해서 테스트 코드를 작성하겠습니다. Fun클래스 안의 정적 함수의 return값을 str변수에 넣는 간단한 작업 입니다.




위 test가 failed가난 궁극적인 이유는 JEST을 TypeScript 테스트를 했기 때문에다. JEST는 JavaScript로 알고 있는데 따로 알려주지 않았기 때문에 TypeScript를 테스트하지를 못하는 것이다.


따라서 아래코드와 같이 JEST를 설정할수 있는 ts파일(jest.config.ts)이 필요하다

// jest.config.ts
import type {Config} from '@jest/types'

const config : Config.InitialOptions = {
roots: ['<rootDir>/src'],
transform: {
'^.+\\.tsx?$': 'ts-jest'
},
testRegex: '(/__test__/.*|(\\.|/)(test|spec))\\.[jt]sx?$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
verbose: true
}

export default config;




참고링크 : https://github.com/facebook/jest/pull/10564

해당 gitHub : https://github.com/Alex-Choi0/node_testing_excercise1.git


다음글 : TypeScript_JEST TypeScript로 Node TestCast만들기 : 실제 테스트 진행 -2

댓글

이 블로그의 인기 게시물

Lesson 12_1 프로퍼티 노드(Property Node)

DAQ로 전압 측정하기-2

Lesson 12_2 참조를 이용한 프로퍼티노드(Property Node)