Jest 사용법 - asynchonous

공식문서에 있는 예제를 통해 기본적인 사용법을 빠르게 익힌다. 따라서 모든 내용은 공식 문서 기반이며, 추후에 테스트를 많이 작성하면서 발생한 엣지 케이스를 이 내용에 덧붙여 추가할 예정이다.

테스트 예제

export async function fetchPostData(postNumber) {
  const res = await fetch(
    `https://jsonplaceholder.typicode.com/posts/${postNumber}`
  );
  if (!res.ok) {
    throw Error('error');
  }
  return res.json();
}

비동기 코드 테스트

비동기 코드가 있을 경우 Jest는 테스트중인 코드가 언제 완료되었는지 알아야 다른 테스트로 이동할 수 있다. 그래서 아래와 같은 방법들을 제공한다.

콜백(Callback)

가장 일반적인 비동기 패턴이다. Jest는 테스트를 완료하기 전에 done콜백이 호출될 때까지 기다린다.

describe("fetchPostData(1)를 호출했고", () => {
  describe("응답 데이터를 정상적으로 받았을때", () => {
    test("the data is firstPost", (done) => {
      function callback(data) {
        try {
          expect(data).toEqual(firstPost);
          done();
        } catch (err) {
          done(err);
        }
      }
      fetchPostData(1).then((data) => callback(data));
    });
  });
});

만약 done()이 호출되지 않으면, 시간 초과 오류가 발생하여 테스트가 실패한다.

프라미스(Promise)

테스트에서 프라미스가 반환되면, Jest가 그 프라미스가 해결될 때까지 기다린다. 프라미스가 거부되면 테스트는 자동으로 실패한다.

test("the data is firstData", () => {
  return fetchPostData(1).then((data) => {
    expect(data).toEqual(firstPost);
  });
});

promise를 반드시 return 해야한다.

return문을 생략하면, 프라미스가 resolves에서 데이터를 반환되기 전에 테스트가 완료되버린다.

만약 프라미스가 실패될 것으로 예상했다면, .catch 메서드를 사용하면 된다.

test("the fetch fails", () => {
  expect.assertions(1);
  return fetchPostData(1111).catch((e) => expect(e.message).toMatch('error'));
});

또한 expect문에서 .resolves.rejects문을 사용할 수 있다.

test("the data is firstData", () => {
  return expect(fetchPostData(1)).resolves.toEqual(firstPost)
});

test("the fetch fails", () => {
  return expect(fetchPostData(1111)).rejects.toThrow();
});

Async/Await

일반적인 async/await 방식과 동일하다.

test("the data is firstData", async () => {
  const data = await fetchPostData(1);
  expect(data).toEqual(firstPost);
});

test("the fetch fails", async () => {
  expect.assertions(1);
  try {
    await fetchPostData(1111);
  } catch (e) {
    expect(e.message).toMatch('error')
  }
});

Last updated