Matcher
Jest의 Metcher는 다양한 방법으로 값을 테스트할 수 있게 해주는 메서드.
모든 Matcher는 expect() 함수와 함께 사용되어 테스트 값이 특정 조건을 만족하는지 검증한다.
기본구조
expect(테스트할_값).Matcher(기대하는_값)
Matcher 기본 개념
describe('Basic Matcher Concepts', () = {
it('기본적인 매칭 도구 사용법', () => {
// 1. 일반적인 matcher 사용
expect(2 + 2).toBe(4);
// 2. 부정 matcher 사용
expect(2 + 2).not.toBe(5);
// 3. 여러 조건 체이닝
expect('hello').toBeDefined().toBeTruthy();
})
})
Matcher의 종류별 사용법
기본값 테스트
describe('Basic Value Testing', () => {
it('shows basic value matching', () => {
// 정확한 값 비교
expect(2 + 2).toBe(4);
// null 체크
expect(null).toBeNull();
// undefined 체크
expect(undefined).toBeUndefined();
// 정의됨 체크
expect("hello").toBeDefined();
});
});
진실성 테스트
describe('Truthiness Testing', () => {
it('shows truthiness matching', () => {
// 참 값 체크
expect(true).toBeTruthy();
// 거짓 값 체크
expect(false).toBeFalsy();
// null이 아님을 체크
expect("hello").not.toBeNull();
});
});
숫자 비교
describe('Number Comparison', () => {
it('shows number matching', () => {
const value = 10;
// 크다
expect(value).toBeGreaterThan(9);
// 크거나 같다
expect(value).toBeGreaterThanOrEqual(10);
// 작다
expect(value).toBeLessThan(11);
// 작거나 같다
expect(value).toBeLessThanOrEqual(10);
});
});
Matcher 사용 시 주요 개념
동등성 비교
describe('Equality Comparison', () => {
it('demonstrates equality matching', () => {
// 1. toBe() - 원시 타입 비교 (===)
expect(1).toBe(1);
expect('hello').toBe('hello');
// 2. toEqual() - 값 비교 (재귀적 비교)
expect({a: 1}).toEqual({a: 1});
expect([1, 2]).toEqual([1, 2]);
// 3. toStrictEqual() - 엄격한 비교
class Test {
constructor(value) {
this.value = value;
}
}
expect(new Test(1)).toStrictEqual(new Test(1));
});
});
부분 일치 비교
describe('Partial Matching', () => {
it('shows partial matching', () => {
// 문자열 포함 여부
expect('hello world').toContain('world');
// 배열 요소 포함 여부
expect([1, 2, 3]).toContain(2);
// 객체 부분 일치
expect({name: 'John', age: 30})
.toMatchObject({name: 'John'});
});
});
Matcher 심화 개념
에러 처리
describe('Error Handling', () => {
it('demonstrates error matching', () => {
// 에러 발생 여부
expect(() => {
throw new Error('test error');
}).toThrow();
// 특정 에러 메시지 체크
expect(() => {
throw new Error('specific error');
}).toThrow('specific error');
});
});
비동기 처리
describe('Async Handling', () => {
it('demonstrates async matching', async () => {
// Promise 성공 케이스
await expect(Promise.resolve('success'))
.resolves.toBe('success');
// Promise 실패 케이스
await expect(Promise.reject('error'))
.rejects.toBe('error');
});
});
모범 사례
적절한 Matcher 선택
describe('Matcher Selection', () => {
it('shows proper matcher selection', () => {
// 원시 타입에는 toBe 사용
expect(1).toBe(1);
// 객체 비교에는 toEqual 사용
expect({a: 1}).toEqual({a: 1});
// 부동소수점 비교에는 toBeCloseTo 사용
expect(0.1 + 0.2).toBeCloseTo(0.3);
});
});
명확한 테스트 작성
describe('Clear Testing', () => {
it('demonstrates clear test writing', () => {
const result = someFunction();
// 긍정적인 케이스 먼저 테스트
expect(result).toBeDefined();
// 구체적인 값 테스트
expect(result).toBe(expectedValue);
// 필요한 경우 여러 관점에서 테스트
expect(result).toBeGreaterThan(0);
expect(result).toBeLessThan(100);
});
});
'Programming > Nest.js' 카테고리의 다른 글
NestJS, React, TypeORM, PostgreSQL 사용해서 게시판 만들기(1) (6) | 2024.11.08 |
---|---|
NestJS TypeORM으로 DB(PostgreSQL) 연결하기 (1) | 2024.11.07 |
Jest로 NestJS 코드 테스트 작성(1) (1) | 2024.11.05 |
NestJS Dto? Pipe? Partial? (0) | 2024.10.31 |
NestJS Service 란?(2) (0) | 2024.10.30 |