Testing Asynchronous Code[Jest]

SnowCat·2023년 2월 24일
0

Jest

목록 보기
3/6
post-thumbnail

Promises

  • 테스트 함수가 프로미스 값을 사용하는 경우, 따로 처리를 하지 않는 경우 데이터는 resolve 되야하고 reject 발생시 fail 처리됨
  • 프로미스로 reject값을 받아오고 싶은경우 catch문으로 처리
test('the data is peanut butter', () => {
  return fetchData().then(data => { // 예상값은 return에 넣어두어야 함
    expect(data).toBe('peanut butter');
  });
});


test('the fetch fails with an error', () => {
  expect.assertions(1); // 하나의 함수가 실행되야 한다는 뜻
  return fetchData().catch(e => expect(e).toMatch('error'));
});

Async/Await

  • async, await 역시 사용 가능
test('the data is peanut butter', async () => {
  const data = await fetchData();
  expect(data).toBe('peanut butter');
});

test('the fetch fails with an error', async () => {
  expect.assertions(1);
  try {
    await fetchData();
  } catch (e) {
    expect(e).toMatch('error');
  }
});
  • 프로미스와의 결합도 가능
test('the data is peanut butter', async () => {
  await expect(fetchData()).resolves.toBe('peanut butter');
});

test('the fetch fails with an error', async () => {
  await expect(fetchData()).rejects.toMatch('error');
});

Callbacks

  • Jest는 함수의 마지막줄까지 함수를 읽으면 테스트를 종료함
test('the data is peanut butter', () => {
  function callback(error, data) {
    if (error) {
      throw error;
    }
    expect(data).toBe('peanut butter');
  }

  fetchData(callback); //콜백함수를 실행하지 않고 테스트 종료
});
  • 콜백함수를 테스트하기 위해서는 done을 사용해야 함
  • 테스트에서 done() 콜백이 호출되면 테스트가 종료되고, 만약 호출되지 않으면 timeout error를 발생시킴
test('the data is peanut butter', done => {
  function callback(error, data) {
    if (error) {
      done(error);
      return;
    }
    try {
      expect(data).toBe('peanut butter');
      done();
    } catch (error) {
      done(error);
    }
  }

  fetchData(callback);
});
profile
냐아아아아아아아아앙

0개의 댓글