Jest 2 Matcher

Jest 2 - Matcher

์ฃผ๋กœ ํ•จ์ˆ˜๋ฅผ ๊ฒ€์‚ฌํ•˜๊ฑฐ๋‚˜ ๋ชจ๋‹ˆํ„ฐ๋ง ํ• ๋•Œ ์‚ฌ์šฉํ•˜๋Š” Matcher๋‹ค. ํ•จ์ˆ˜๋ฅผ ๊ฒ€์‚ฌํ• ๋•Œ ๋˜ React, React Native์—์„œ ์ž์ฃผ ์‚ฌ์šฉํ•˜๋Š” ํ…Œ์Šค ๊ธฐ๋ฒ•์ธ snapshot์„ ์‚ฌ์šฉํ• ๋•Œ ๊ผญ ํ•„์š”ํ•œ ๊ธฐ๋Šฅ์ด ์žˆ๋Š”๋ฐ jest์—์„œ ์ œ๊ณตํ•˜๋Š” mockํ•จ์ˆ˜๋‹ค.

์‚ฌ์šฉ๋ฒ•

// ์•„๋ž˜์™€ ๊ฐ™์ด jest.fn()์œผ๋กœ ์ฃผ๋ฉด ๋œ๋‹ค.
const mockFunction = jest.fn();

// ์•„๋ž˜์ฒ˜๋Ÿผ return๊ฐ’์„ ์ง€์ •ํ•ด ์ค„์ˆ˜ ์žˆ๋‹ค
const hasReturn = jest.fn(() => 1);

Matcher


toBeCalled & toHaveBeenCalled

ํ˜ธ์ถœ ์—ฌ๋ถ€
const mockFunction = jest.fn();
mockFunction();

test('ํ•จ์ˆ˜ ํ˜ธ์ถœ ์—ฌ๋ถ€', () => {
  // ์ด๋ฆ„๋งŒ ๋‹ค๋ฅด๊ณ  ๊ธฐ๋Šฅ์€ ๋™์ผ
  expect(mockFunction).toBeCalled();
  expect(mockFunction).toHaveBeenCalled();
});

toBeCalledTimes & toBeCalledWith

ํ˜ธ์ถœ ํšŸ์ˆ˜, ํ˜ธ์ถœ์‹œ ์ธ์ž๊ฐ’ ํ™•์ธ
const mockFunction = jest.fn();
mockFunction();

test('ํ•จ์ˆ˜ ํ˜ธ์ถœ ์—ฌ๋ถ€', () => {
  // ๋ช‡๋ฒˆ ํ˜ธ์ถœ
  expect(mockFunction).toBeCalledTimes(1);
  // ์–ด๋–ค ์ธ์ž ๊ฐ’๊ณผ ํ˜ธ์ถœ
  expect(mockFunction).toBeCalledWith();
});

toReturn & toHaveReturned

return ๊ฐ’ ํ™•์ธ
test('ํ•จ์ˆ˜ ๋ฐ˜ํ™˜ ์—ฌ๋ถ€', () => {
  const hasReturn = jest.fn(() => 1);

  hasReturn();
  // ์ด๋ฆ„๋งŒ ๋‹ค๋ฅด๊ณ  ๊ธฐ๋Šฅ์„ ๋™์ผ
  expect(hasReturn).toReturn();
  expect(hasReturn).toHaveReturned();
});

toReturnTimes & toHaveReturnedTimes

return ํ˜ธ์ถœ ์—ฌ๋ถ€
test('ํ•จ์ˆ˜ ๋ฐ˜ํ™˜ ์—ฌ๋ถ€', () => {
  const hasReturn = jest.fn(() => 1);

  hasReturn();

  // ๋น„๊ต ๊ฐ’์„ ๋ช‡๋ฒˆ์„ ๋ฐ˜ํ™˜ํ–ˆ๋Š”์ง€, ์ด๋ฆ„๋งŒ ๋‹ค๋ฅด๊ณ  ๊ธฐ๋Šฅ์€ ๋™์ผ
  expect(hasReturn).toReturnTimes(1);
  expect(hasReturn).toHaveReturnedTimes(1);
});

๋น„๋™๊ธฐ ํ•จ์ˆ˜ ํ…Œ์ŠคํŠธ

promise, async & await, callback์„ ๊ฒ€์‚ฌํ•˜๊ธฐ
test('done์„ ์ด์šฉํ•ด ๊ฒ€์‚ฌํ•˜๊ธฐ', done => {
  function callback(data) {
    try {
      expect(data).toBe('peanut butter');
      done();
    } catch (error) {
      done(error);
    }
  }

  fetchData(callback);
});

test('Promise์—์„œ ๊ฒ€์‚ฌํ•˜๊ธฐ', () => {
  return fetchData().then(data => {
    expect(data).toBe('peanut butter');
  });
});

test('Promise์—์„œ ๊ฒ€์‚ฌํ•˜๊ธฐ', () => {
  return expect(fetchData()).resolves.toBe('peanut butter')
});

test('async & await ๊ฒ€์‚ฌํ•˜๊ธฐ', async () => {
  const data = await fetchData();
  expect(data).toBe('peanut butter');
});

test('async & await ๊ฒ€์‚ฌํ•˜๊ธฐ', async () => {
  await expect(fetchData()).resolves.toBe('peanut butter');
});