-
Notifications
You must be signed in to change notification settings - Fork 1
Jest Tutorial
B edited this page Dec 22, 2022
·
20 revisions
자바스크립트 테스트 프레임워크인 Jest 가이드 문서입니다.
- 노드 기반의 프로젝트 생성
npm init -y
# yarn init -y
- jest 설치
npm i jest --save-dev
# yarn add jest --dev
- 커맨드라인에서 npm script 설정
# package.json
{
"scripts":{
"test" : "jest"
}
}- Jest가 설치되면 프로젝트의 루트에 jest.config.js 파일을 생성 및 구성
이 파일에서는 테스트 환경, 테스트 정규식 패턴 등과 같은 다양한 Jest 구성 옵션을 지정할 수 있습니다.
옵션 더보기
// jest.config.js
module.exports = {
testEnvironment: 'node'
};- 테스트 파일은
__tests__디렉토리에 배치해야 하며 파일 이름은.test.js또는.spec.js로 끝나야 합니다. - 테스트를 작성하려면 Jest의
test함수를 사용하면 됩니다.
// 기본 구조
test('describe test', () => {
const actual = someFunction();
const expected = someExpectedValue;
expect(actual).toEqual(expected);
});matchers 목록
expect 함수는 matchers와 함께 사용됩니다.
| Matchers | |
|---|---|
| 1 | toBe |
| 2 | toEqual |
| 3 | toBeNull |
| 4 | toBeUndefined |
| 5 | toBeDefined |
| 6 | toBeTruthy |
| 7 | toBeFalsy |
| 8 | toContain |
| 9 | toMatch |
| 10 | toBeLessThan |
| 11 | toBeLessThanOrEqual |
| 12 | toBeGreaterThan |
| 13 | toBeGreaterThanOrEqual |
| 14 | toBeCloseTo |
| 15 | toThrow |
// __test__/unit.test.js
test('adding two numbers', () => {
const result = 3 + 2;
expect(result).toBe(3);
});- 테스트 실행 및 결과확인
npm run test
# yarn run test$ jest
FAIL __test__/unit.test.js
✕ adding two numbers (2 ms)
● adding two numbers
expect(received).toBe(expected) // Object.is equality
Expected: 3
Received: 5
1 | test('adding two numbers', () => {
2 | const result = 3 + 2;
> 3 | expect(result).toBe(3);
| ^
4 | });
5 |
at Object.toBe (__test__/test.test.js:3:20)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.265 s, estimated 1 s
Ran all test suites.더 나아가서
// group.test.js
// `src` 디렉토리에서 game.js 불러온 후
const bowlingGame = require("../src/game");
// describe 함수를 이용해서 각 테스트 케이스를 그룹화합니다.
describe("Bowling tests", ()=>{
test('테스트1', () => {
});
test('테스트2', () => {
});
})참고: Jest CLI options
Code Kata의 wiki 입니다.