TDD

Matchers

JoyYellow 2022. 12. 19. 18:05

Matchers (일치자) 사용

Jest는 Matchers를 사용하여 다양한 방법으로 값을 검증할 수 있습니다. 이 문서에서는 일반적으로 사용되는 몇 가지 Matchers(일치자) 항목을 소개합니다. 전체 목록은 expect API 문서를 참조하십시오.


기본 Matchers

값을 검증하는 가장 간단한 방법은 정확한 동일성을 사용하는 것입니다.

tes('two plus two is four', () => {
	expect(2 + 2).toBe(4);
});

이 코드에서 expect(2 + 2)는 expectation 객체를 리턴한다. 일반적으로 이러한 expectation 객체에 대한 콜 매치를 제외하고는 많은 작업을 수행하지 못합니다. 이 코드에서 .toBe(4)는 matcher입니다. jest를 실행할 때 오류 메시지 출력을 위해 모든 실패 matchers를 기록합니다. toBeOjbect.is를 사용하여 정확한 동등성을 테스트합니다. 개체 값을 확인하려면 대신 toEqual또는 toStrictEqual을 사용합니다.

test('object assignment', () => {
	const data = {one: 1};
    data['two'] = 2;
    expect(data).toEqual({one: 1, two: 2});
});

toEqual은 특이하게 객체 또는 배열의 모든 필드를 확인한다.

 

💡 Tip
toStrictEqual을 사용하는 것이 toEqual을 사용하는 것보다 더 선호됩니다. toEqual은 정의되지 않는 값을 무시하는 반면, toStrictEqual은 이러한 값을 고려합니다.

 

not을 사용해 macher의 반대를 테스트 할 수 있습니다.

test('adding prositive numbers is not zero', () => {
	for (let a = 1; a < 10; a++) {
    	for (let b = 1; b < 10; b++) {
        	expect(a + b).not.toBe(0);
        }
    }
});

Truthiness(진실성)

가끔 테스트 할 때 undefined, null 그리고 false를 구분해야할 때가 있습니다. 또는 이들을 다르게 처리하고 싶지 않을 때도 있습니다. jest에는 원하는 것을 명시적으로 표현할 수 있는 helpers를 제공합니다.

  • toBeNullnull과 일치
  • toBeUndefinedundefined와 일치
  • toBeDefinedtoBeUndefined의 반대
  • toBeTruthy는 상태가 true인 것과 일치
  • toBeFalsy는 상태가 false인 것과 일치
test('null', () => {
    const n = null;
    expect(n) = null;
    expect(n).toBeNull();
    expect(n).toBeDefined();
    expect(n).not.toBeUndefined();
    expect(n).not.toBeTruthy();
    expect(n).toBeFalsy();
});

test('zero', () => {
    const z = 0;
    expect(z).not.toBeNull();
    expect(z).toBeDefined();
    expect(z).not.toBeUndefined();
    expect(z).not.toBeTruthy();
    expect(z).toBeFalsy();
});

코드에 따라 정확하게 일치하는 matcher를 사용해야 합니다.

 


Numbers

숫자를 비교하는 대부분의 방법에는 일치하는 값이 있습니다.

test('two plus two', () => {
    const value = 2 + 2;
    expect(value).toBeGraterThan(3);
    expect(value).toBeGraterThanOrEqual(3.5);
    expect(value).toBeLessThan(5);
    expect(value).toBeLessThanOrEqual(4.5);
    
    // toBe and toEqual are equivalent(동등한) for numbers
    expect(value).toBe(4);
    expect(value).toEqual(4);
});

부동 소수점 동일성의 경우 작은 반올림 오차에 의존하는 검증을 원하지 않기 때문에 toEqual 대신 toBeCloseTo를 사용합니다.

test('adding floating point numbers', () => {
    const value = 0.1 + 0.2;
    // expect(value).toBe(0.3); this won't work because of rounding error(반올림 오차)
    expect(value).toBeCloseTo(0.3); // this works.
});

 


Strings

문자열을 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/);
});

 


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);
    
    // You can also use a string that must be contained in the error message or regexp
    expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
    expect(() => compileAndroidCode()).toThrow(/JDL/);
    
    // Or you can match an exact error message using a regexp like below
    expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK$/); // test fails
    expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK!$/); // tes pass
});

 

💡 Tip
예외를 발생시키는 함수는 래핑 함수 내에서 호출되어야 합니다. 그렇지 않으면 toThrow assertion이 실패합니다.

 


더 보기

Matchers(일치자) 전체 목록은 참조 문서를 참조하십시오.

사용할 수 있는 Matchers에 대해 알게 되었으니 다음 단계로 Jest가 비동기 코드를 테스트할 수 있는 방법에 대해 소개 하겠습니다.