본문 바로가기

Testing

Mocha, chai, jsdom을 활용한 JS 테스팅(3) - custom event dispatch

드디어 JS 테스팅의 마지막 이해 단계인 커스텀 이벤트 디스패치 단계까지 왔다.

 

참고자료

 

코드를 먼저 보자.

   const getButtonBy = function (text, buttons) {
      const result = buttons.filter(function (button) {
        return button.textContent === text;
      });

      if (result.length > 1) {
        throw new Error("no extra buttons allowed");
      } else if (result.length < 1) {
        throw new Error("no button");
      }

      return result[0];
    };

    const clickEvent = new window.MouseEvent("click", {
      bubbles: true,
      cancelable: true,
      view: window
    });
    describe("Step 1 - 숫자 버튼을 누르고 화면에 숫자를 입력하기", function () {
      it("처음 숫자 버튼을 눌렀을 때, 첫 번째 화면에 누른 숫자가 보여야 합니다.", function (done) {
        const test = ["3", "3"];
        const clicks = test.slice(0, -1);
        const expected = test.slice(-1)[0];
        const display = window.document.querySelector(".calculator-display");
        clicks.forEach(function (click) {
          const button = getButtonBy(click, allButtons);
          button.dispatchEvent(clickEvent);
        });
        expect(display.textContent).to.equal(expected);
        done();
      });

 

clicks.forEach로 순회하면서 getButtonBy 함수를 실행해서 button에 담았다. 코드를 살펴보면 변수 button에는 변수 clicks에 담겨있는 텍스트와 일치하는 buttons의 요소를 담고 그 요소를 실제 계산기에서 눌러주는 이벤트를 실행하는 것을 알 수 있다.

 

button.dispatchEvent(clickEvent);

const clickEvent = new window.MouseEvent("click", {
  bubbles: true,
  cancelable: true,
  view: window
});

 

new window.MouseEvent로 click이벤트를 하난 만든 것을 알 수 있다. 이벤트 핸들러의 이름은 clickEvent이다.

button.dispatchEvent 함수는 생성한 이벤트 객체를 호출해서 이벤트를 반드시 실행시켜 준다.(dispatch는 일을 '처리하다' 의미이다.)

 

MouseEvent를 만들면서 여러가지 플래그를 넣을 수 있다.(버블링 등)

 

아무튼 click한 요소를 실제 계산기에서 실행시켜서 계산기 화면에 띄워지게 되고 expected와 일치 여부를 비교할 수 있게 되는 것이다.

 

커스텀 이벤트를 작성하기 위해서는 다양한 이벤트가 있다. 아래를 참고하자.

 

  • UIEvent
  • FocusEvent
  • MouseEvent
  • WheelEvent
  • KeyboardEvent

 

이것으로

Mocha, chai, jsdom을 활용한 JS 테스팅

포스팅을 마치도록 한다.