Jest 사용법 - Matchers

Jin·2022년 6월 22일
0

jest

목록 보기
1/4
post-thumbnail

Common Matchers

toBe

  • 값을 비교하거나 Object 인스턴스의 참조 ID를 체크 가능

toEqual

  • 객체 인스턴스의 모든 속성을 재귀적으로 비교 가능

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

toBeGraterThan

  • 보다 큰 숫자인지 확인

toBeGraterThanOrEqual

  • 크거나 같은지 확인

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

  // toBe and toEqual are equivalent for numbers
  expect(value).toBe(4);
  expect(value).toEqual(4);
});
  • 소수점을 확인할때는 rounding error 때문에 toEqual, toBe 대신 toBeCloseTo를 사용하는 것이 좋다.
test('adding floating point numbers', () => {
  const value = 0.1 + 0.2;
  //expect(value).toBe(0.3);   라운딩 에러때매 테스트 실패
  expect(value).toBeCloseTo(0.3);
});

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

  • Array 도는 iterables 한 객체에 특정 요소 포함 여부 확인
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/);
});

reference : https://jestjs.io/docs/using-matchers

profile
내가 다시 볼려고 작성하는 블로그. 아직 열심히 공부중입니다 잘못된 내용이 있으면 댓글로 지적 부탁드립니다.

0개의 댓글