Bruno의 jest 강의 2 (비동기 통신 테스트)

YEONGHUN KO·2022년 8월 13일
0

JAVASCRIPT TESTING

목록 보기
4/11
post-thumbnail

React Async Testing using React Testing Library Introduction

비동기 통신을 기다려야하는 경우 beforeEach에서 await를 하는게 좋다.

테스트 할때마다 D라는 데이터를 비동기통신으로 받아와야 하는 경우가 있다고 하자. 그럼 beforeEach에 D를 await하는 코드를 짜는게 훨씬 효율적이다. 아래 코드와 같이 말이다.

// default count가 10인 상태!
describe('when the incrementor changes to 5 and "+" button is clicked', () => {
  // 첫번째 beforeEach
  beforeEach(async () => {
    user.type(screen.getByLabelText(/Incrementor/), '{selectall}5');
    user.click(screen.getByRole('button', { name: 'Add to Counter' }));
    await screen.findByText('Current Count: 15');
  });

  it('renders "Current Count: 15"', () => {
    expect(screen.getByText('Current Count: 15')).toBeInTheDocument();
  });

  // Documentation: https://testing-library.com/docs/guide-disappearance/##waiting-for-disappearance
  // eslint-disable-next-line jest/expect-expect
  it('"I am too small" disappears after 300ms', async () => {
    await waitForElementToBeRemoved(() => screen.queryByText('I am too small'));
  });

  describe('when the incrementor changes to empty string and "+" button is clicked', () => {
    // 두번째 beforeEach
    beforeEach(async () => {
      user.type(screen.getByLabelText(/Incrementor/), '{selectall}{delete}');
      user.click(screen.getByRole('button', { name: 'Add to Counter' }));
      await screen.findByText('Current Count: 16');
    });

    it('renders "Current Count: 16"', () => {
      expect(screen.getByText('Current Count: 16')).toBeInTheDocument();
    });
  });
});

+를 클릭하면 비동기 통신을 통해 incrementor에 따른 숫자를 받아오는 앱이라고 할때, 맨처음 beforeEach에서 숫자 15가 들어오고 두번째 beforeEach에서는 16이라는 숫자가 비동기 통신으로 받아온다.

이렇게 beforeEach로 미리 비동기 데이터를 받아오면 매 테스트 할때마다 비동기 데이터를 받아오는 코드를 적지 않아도 된다. beforeEach를 잘 활용하여 코드 중복을 최소화 해보자!

waitForElementToBeRemoved

위의 코드에도 잠깐 나왔다. target element가 원래 있었다가 사라질경우 감지를 하는 api이다. 그래서 원래 랜더링되어있지 않으면 에러를 내뱉는다.

profile
'과연 이게 최선일까?' 끊임없이 생각하기

0개의 댓글