npm install --save-dev jest
두 수를 더하는 hypothetical fuction에 대한 test 적는 방법
function sum(a, b) {
return a + b;
}
module.exports = sum;
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
{
"scripts": {
"test": "jest"
}
}
마지막으로, npm test를 실행하면 Jest가 이 message를 print 해준다.
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)
이 테스트는 expect와 toBe를 두 values가 정확히 identical한 지 test에 사용했습니다.
CLI에서 jest를 직접 사용할 수 있다.
how to run Jest on files matching my-test, using config.json as configuration file and display a native OS notification after the run:
jest my-test --notify --config=config.json
project에 기반하여, Jest는 몇 가지 질문을 요청하고 각 option에 대한 짧은 설명과 basic configuration을 만들어줄 것이다.
npm init jest@latest
install required dependencies:
npm install --save-dev babel-jest @babel/core @babel/preset-env
Configure Babel to target your current version of Node by creating a babel.config.js file in the root of your project:
babel.config.js
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};
The ideal configuration for Babel will depend on your project.
Jest can be used in projects that use webpack to manage assets, styles, and compilation. webpack does offer some unique challenges over other tools.
... 생략
Via bebel
Jest supports TypeScript, via Babel. First, make sure you followed the instructions on using Babel above. Next, install the @babel/preset-typescript:
npm install --save-dev @babel/preset-typescript
Then add @babel/preset-typescript to the list of presets in your babel.config.js.
babel.config.js
module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-typescript',
],
};
하지만, 여기엔 몇 caveats가 Babel과 함께 TypeScript를 사용하기 위해 있다.
왜냐하면 Babel에서 지원하는 타입 스크립트는 순수하게 transpilation이고, Jest는 실행하는 test의 type을 체크하지 않는다. 만약 원한다면, ts-jest를 대신 이용할 수 있다. 또는 그냥 타입 스크립트 컴파일러 tsc를 따로 실행할 수 있다.
Via ts-jest
ts-jest is a TypeScript preprocessor with source map support for Jest that lets you use Jest to test projects written in TypeScript.
npm install --save-dev ts-jest
In order for Jest to transpile TypeScript with ts-jest, you may also need to create a configuration file.
Type definitions
There are two ways to have Jest global APIs typed for test files written in TypeScript.
You can use type definitions which ships with Jest and will update each time you update Jest. Install the @jest/globals package:
npm install --save-dev @jest/globals
and imoirt the APIs from it:
sum.test.ts
import {describe, expect, test} from '@jest/globals';
import {sum} from './sum';
describe('sum module', () => {
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
});
또는 @types/jest package를 설치하는 것을 선택할 수 있다. 이것은 import할 필요 없이 Jest globals에게 타입을 제공한다.
npm install --save-dev @types/jest