matchers를 활용하여 여러 방법으로 테스트가 가능하다.
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
expect()
는 "expectation" 객체를 반환한다. expectation
객체로 별로 따로 하는 것은 보통 없고 주로 matchers를 호출하기 위해 사용한다.
toBe()
이런 게 matcher다. jest가 실행되면 이러한 matcher들을 전부 실행하고 실패 혹은 성공 메시지가 출력된다.
toBe()
는 같음을 증명하기 위한 matcher다. toBe()
는 Object.is
를 사용한다. 따라서 단순히 원시값이 같음을 증명하고 싶을 때 사용한다.
toEqual()
은 객체 혹은 배열의 모든 필드를 재귀적으로 확인한다. 따라서 객체가 동일함을 증명하려면 toEqual()
matcher를 사용해야 한다.
🚨
toEqaul()
matcher는undefined
값을 갖는 객체의 키 및 배열 요소를 무시한다.
또한 희소 배열이거나 객체 타입이 다르다면 무시된다.
따라서 이러한 경우를 위해서는toStrictEqual()
matcher를 사용한다.
matcher 결과의 부정(negate)를 위해 사용한다.
테스트를 할 때 undefined
, null
, false
값을 구별이 필요한 경우가 있다. 혹은 이 값들을 구별하고 싶지 않을 때도 있다.
jest에서는 명시적으로 원하는 값을 구분하기 위한 matcher들을 가지고 있다.
test('null', () => {
const 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();
});
null
과 같은 값인지 증명한다.
undefined
와 같은 값인지 증명한다.
undefined
가 아닌 값인지 증명한다.
if
문에서 true
로 평가되는 값인지 증명한다.
if
문에서 false
로 평가되는 값인지 증명한다.
test('two plus two', () => {
const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(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);
});
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.
});
소수점 테스트 시 toBeCloseTo
를 사용해야 한다.
test('there is no I in team', () => {
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph', () => {
expect('Christoph').toMatch(/stop/);
});
문자열 검증은 정규표현식으로 가능하다.
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');
});
배열 혹은 iterable이 특정 아이템을 포함하는 지 검증하려면 toContain
matcher를 사용한다.
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 a regexp
expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
expect(() => compileAndroidCode()).toThrow(/JDK/);
// 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!$/); // Test pass
});
특정 에러가 발생해야 한다면 toThrow
matcher를 사용하면 된다.
jest api 문서에서 더 많은 matcher들을 확인할 수 있다.