Jest란?
Jest는 페이스북에서 만들어서 React와 더불어 많은 자바스크립트 개발자들로부터 좋은 반응을 얻고 있는 테스팅 라이브러리라고 한다. zero config라고 해서 별도의 설정 없이 빠르게 테스트 케이스를 작성할 수 있다는 장점을 가지고 있다.
Jest 설치
npm i -D jest
설치를 완료한 뒤, package.json의 test script를 jest로 수정해 주면 된다. 이후 npm test로 실행하여 테스트 코드를 실행하면 되는데, 이때 실행되는 파일들은 아래와 같다.
- 파일명.test.js 혹은 __tests__ 폴더 안에 있는 파일들
test코드 작성 방식
1. 실행 함수를 외부 파일에서 가져오지 않을 때
add.test.js
describe('계산 테스트', () => {
const a = 1, b = 2;
test('a + b는 3이다.', () => {
expect(a + b).toEqual(3);
});
});
/*
describe('그룹 테스트 설명 문자열', () => {
const a = 1, b = 2; // 테스트에 사용할 일회용 가짜 변수 선언
test('개별 테스트 설명 문자열', () => {
expect(검증대상).toXxx(기대결과);
});
});
*/
2. 함수를 외부 파일에서 가져올 때
fn.js
const fn = {
add : (num1, num2) => (num1 + num2)
}
module.exports = fn;
fn.test.js
const fn = require('./fn')
test("2 더하기 3은 5", () => {
expect(fn.add(2, 3)).toEqual(5)
})
Macher
Common
toBe | 숫자나 문자 등 기본타입값을 사용할 때
toEqual | 객체 또는 배열의 모든 필드를 재귀적으로 검사한다. 단, toEqual은 정의되지 않은 속성, 정의되지 않은 배열 항목, 배열 희소성 또는 객체 유형 불일치가 있는 객체 키를 무시하기 때문에, 이를 고려하려면 toStrictEqual을 사용해야 한다.
Truthiness
toBeNull | null 값인지
toBeUndefined | undefined인지
toBeDefined | toBeUndefined의 반대
toBeTruthy | true인지
toBeFalsy | false인지
Number
toBeGreaterThan | 크다
toBeGreaterThanOrEqual | 크거나 같다
toBeLessThan | 작다
toBeLessThanOrEqual | 작거나 같다
toBeCloseTo | 숫자를 더할 때 정수가 아니라 실수인 경우. toBe는 작동하지 않는다.
test("ID는 10자 이하여야 합니다.", () => {
const ID = "TEST_TEST_TEST"
expect(ID.length).toBeLessThanOrEqusl(10);
})
=> Error // ID가 10자 이상이기 때문에 오류가 난다
String
toMatch | 정규식에 대해 문자열을 확인
test('there is no I in team', () => {
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph', () => {
expect('Christoph').toMatch(/stop/);
});
대소문자 구분을 하기 때문에 구분 없이 확인을 하고 싶다면 정규표현식 뒤에 i를 붙이면 된다. ex) /a/i
Arrays and iterables
toContain | 배열이나 이터러블에 특정 항목이 포함되어 있는지
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'milk',
];
test('the shopping list has milk on it', () => {
expect(shoppingList).toContain('milk');
expect(new Set(shoppingList)).toContain('milk');
});
Exceptions
toThrow | 특정 함수가 호출될 때 오류를 발생시키는지 여부를 테스트
function compileAndroidCode() {
throw new Error('you are using the wrong JDK!');
}
test('compiling android goes as expected', () => {
expect(() => compileAndroidCode()).toThrow();
expect(() => compileAndroidCode()).toThrow(Error);
});
'일하면서 공부해욧' 카테고리의 다른 글
Delete `␍` eslint (prettier/prettier) (0) | 2023.07.01 |
---|---|
custom class validator (0) | 2023.06.25 |
node.js와 express (0) | 2023.06.18 |
class validator와 DTO, 그리고 직렬화/역직렬화 (0) | 2023.06.11 |
React, TypeScript 그리고 Jest (0) | 2023.05.26 |