Bruno의 jest 강의 5 (form 테스트)

YEONGHUN KO·2022년 8월 15일
0

JAVASCRIPT TESTING

목록 보기
7/11
post-thumbnail

form을 이용한 happy path test

만약 모든 field의 validation이 다 통과되는 경우를 happy path라고 한다. form을 이용해서 happy path를 테스트 한다고 하자. 그럼 submit을 누를경우 micro task로 옮겨진다. 왜냐면 form 태그는 http post/get을 사용하기 때문. 그래서 비동기적으로 코드가 실행된다.

그래서, submit이후에 나타나는 텍스트를 가져오려면 waitFor,findBy를 사용하는게 좋다.

(여기선 waitFor를 써보겠다)

nextbutton이 form submit이다.


describe('MultiStepForm', () => {
  const onSubmit = jest.fn();

  beforeEach(() => {
    onSubmit.mockClear();
    render(<MultiStepForm onSubmit={onSubmit} />);
  });


  it('has 3 required fields on first step', async () => {
    clickNextButton();

    await waitFor(() => {
      expect(getFirstName()).toHaveErrorMessage('Your First Name is Required');
    });

    expect(getCity()).toHaveErrorMessage('city is a required field');
    expect(getSelectJobSituation()).toHaveErrorMessage(
      'You need to select your job situation'
    );
  });
})

function clickNextButton() {
  user.click(screen.getByRole('button', { name: /Next/i }));
}

다른 form을 type한적이 없기에 next 버튼을 눌렀을 때 에러가 난다.
그래서 submit이 다 실행되고 에러메세지가 나타날때까지 기다린다.

그리고 firstName뿐만 아니라 city, jobSituation에 나타나는 에러도 테스트해주면 된다.

참고로 javascript의 모든 event는 async로 작동된다.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing#event_handlers 참고!

테스트 할때 유의사항

  1. 모든 것을 테스트 할 필요가 없다.

    • 딱 필요한것만 테스트해라
  2. describe,it을 통해 테스트를 잘 쪼개자

    • 테스트를 잘 쪼개지 않으면 중복코드가 굉장히 많아져 어디서 무슨 에러가 발생했는지 알아내기 힘들것이다.
    • describe/it을 이용해서 테스트 단위를 잘 분리시키자
    • 그리고 **Each/**All 또는 함수를 이용해서 중복코드도 줄이자
profile
'과연 이게 최선일까?' 끊임없이 생각하기

0개의 댓글