Using Matchers[Jest]

SnowCat·2023년 2월 23일
0

Jest

목록 보기
2/6
post-thumbnail

Common Matchers

  • expect.toBe()는 값이 정확하게 일치하는지 확인
test('two plus two is four', () => {
  expect(2 + 2).toBe(4);
});
  • expect는 expectation 객체를 반환하고, toBe()에서는 Object.is를 사용해 객체가 정확히 일치하는지 확인
  • 값만을 체크하고 싶으면 toEqual 사용
    toEqual은 undefined 속성, undefined 배열 값, array sparseness(선언만 되고 값이 할당되지 않은 배열), 객체의 타입은 무시하게 됨, 이를 체크하기 위해서는 toStrictEqual 사용
test('object assignment', () => {
  const data = {one: 1};
  data['two'] = 2;
  expect(data).toEqual({one: 1, two: 2});
});
  • toBe, toEqual 앞에 not을 붙여서 반대로 matcher 사용 가능
test('adding positive 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

  • toBeNull => null인지 체크
  • toBeUndefined => undefined인지 체크
  • toBeDefined => toBeUndefined인지 체크
  • toBeTruthy => 값이 True가 되는지 체크
  • toBeFalsy => 값이 False가 되는지 체크
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();
});

Numbers

  • 부등호 연산을 위해 toBeGreaterThan, toBeGreaterThanOrEqual, toBeLessThan, toBeLessThanOrEqual가 있음
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);
  expect(value).toBe(4);
  expect(value).toEqual(4);
});
  • 소수점 연산에서 rounding으로 인한 에러를 막기 위해선 toBeCloseTo를 사용 가능
test('adding floating point numbers', () => {
  const value = 0.1 + 0.2;
  expect(value).toBe(0.3); // rounding 문제로 인해 오류 발생
  expect(value).toBeCloseTo(0.3);
});

Strings

정규식을 사용해 문자열도 검사 가능

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);

  // 에러 메시지도 확인 가능
  expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
  expect(() => compileAndroidCode()).toThrow(/JDK/);
  expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK!$/);
});

출처:
https://jestjs.io/docs/using-matchers

profile
냐아아아아아아아아앙

0개의 댓글