티스토리 뷰

Tool/jest

[번역] Jest - Using Matchers

코딩산책 2018. 11. 7. 07:33

버전: Jest 23.6
날짜: 2018-11-06
※ 내용숙지가 안된 번역이 많아, 원문을 함께 둠

Using Matchers

Jest uses "matchers" to let you test values in different ways. This document will introduce some commonly used matchers. For the full list, see the expect API doc.

Jest는 여러가지 방법으로 값을 테스트할 수 있게 "matchers"를 사용한다. 이 문서는 일반적인 matchers를 사용법을 소개 할 것이다. 전체 목록은 expect API doc를 참조 하세요.

Common Matchers

The simplest way to test a value is with exact equality.

값을 가장 단순하게 테스트하는 것은 정확한 동등 이다.

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

In this code, expect(2 + 2) returns an "expectation" object. You typically won't do much with these expectation objects except call matchers on them. In this code, .toBe(4) is the matcher. When Jest runs, it tracks all the failing matchers so that it can print out nice error messages for you.

이코드에서, expect(2 + 2) 는 "expectation" 오브젝트를 리턴한다. 일반적으로 matchers를 호출하는 것을 제외하고는 이런 exectation 오브젝트는 많지 않다. 이 코드에서는 .toBe(4)가 matcher이다. Jest가 실행되면, 모든 실패한 matchers를 추적하여 멋진 에러 메세지를 프린트 할 수 있다.

toBe uses Object.is to test exact equality. If you want to check the value of an object, use toEqual instead:

toBe 는 정확한 동등을(객체 동등) 테스트하기 위해 Object.is 를 사용한다. 만약 오브젝트의 값을 체크하기를 원한다면 대신 toEqual 를 사용해라.

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

toEqual recursively checks every field of an object or array.

toEqual 는 오브젝트 또는 배열의 모든 필드 값을 재귀적으로 체크한다.

You can also test for the opposite of a matcher:

또한 반대의 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

In tests you sometimes need to distinguish between undefinednull, and false, but you sometimes do not want to treat these differently. Jest contains helpers that let you be explicit about what you want.

테스트에서 때때로  undefinednull, and false를 구별해야 하지만, 때로는 다르게 처리하고 싶지 않을때가 있다. Jest는 너가 원하는 것에 대해 명시할 수 있는 헬퍼가 포함되어 있다.

  • toBeNull matches only null
  • toBeUndefined matches only undefined
  • toBeDefined is the opposite of toBeUndefined
  • toBeTruthy matches anything that an if statement treats as true
  • toBeFalsy matches anything that an if statement treats as false

For example:

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

You should use the matcher that most precisely corresponds to what you want your code to be doing.

코드가 하기를 원하는 것과 가장 일치하는 matcher를 사용해야 한다.

Numbers

Most ways of comparing numbers have matcher equivalents.

숫자를 비교하는 일반적인 방법인 동등 matcher 있다.

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

For floating point equality, use toBeCloseTo instead of toEqual, because you don't want a test to depend on a tiny rounding error.

소수점 동일을 위해, 작은 반올림 에러를 일으키는 테스트를 원하지 않기 때문에, 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

You can check strings against regular expressions with toMatch:

 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

You can check if an array contains a particular item using toContain:

toContain를 사용하여 배열에 특별한 item이 포함되어 있는지 확인 할 수 있다:

const shoppingList = [
  'diapers',
  'kleenex',
  'trash bags',
  'paper towels',
  'beer',
];

test('the shopping list has beer on it', () => {
  expect(shoppingList).toContain('beer');
});

Exceptions

If you want to test that a particular function throws an error when it's called, use toThrow.

특정 함수가 호출될 때 에러를 던진다는 것을 테스트하려면 toThrow를 사용하자.


function compileAndroidCode() {
  throw new ConfigError('you are using the wrong JDK');
}

test('compiling android goes as expected', () => {
  expect(compileAndroidCode).toThrow();
  expect(compileAndroidCode).toThrow(ConfigError);

  // You can also use the exact error message or a regexp
  expect(compileAndroidCode).toThrow('you are using the wrong JDK');
  expect(compileAndroidCode).toThrow(/JDK/);
});

And More

This is just a taste. For a complete list of matchers, check out the reference docs.

Once you've learned about the matchers that are available, a good next step is to check out how Jest lets you test asynchronous code.

이 것은 단지 맛보기 입니다, matchers의 전체 항목에 대한 reference docs를 확인 하세요.

일단 사용가능한 matchers에 대해 학습으면, 다음 단계로 Jest가 test asynchronous code를 테스트하는 방법을 확인하는 것이 좋다.


'Tool > jest' 카테고리의 다른 글

[번역] Jest - Testing Asynchronous Code  (0) 2018.11.09
[번역] Jest - Setup and Teardown  (0) 2018.11.08
[번역] Jest - Mock Functions  (0) 2018.11.05
[번역] Jest - An Async Example  (0) 2018.11.03
[번역] Jest - Testing React Native Apps  (0) 2018.11.01
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함