vendredi 9 août 2019

How to test DOM events with Jest

How do you dispatch an event on a DOM element using Jest test suite? I am unable to test the functionality of my component for this reason.

I've searched stack, google, and JSDOM and Jest github issues - no help.

Here's the code of my unit test:

describe("toggle", function() {
    let element;
    let toggle;
    let inner;
    let innerChecked;
    beforeAll(() => {
      element = document.createElement("button");
      element.classList.add("yi-toggle");
      element.setAttribute("id", "my-toggle");

      inner = document.createElement("span");
      inner.classList.add("yi-toggle-inner");
      inner.textContent = "Off";

      innerChecked = document.createElement("span");
      innerChecked.classList.add("yi-toggle-inner__checked");
      innerChecked.textContent = "On";

      element.appendChild(inner);
      element.appendChild(innerChecked);

      toggle = new Toggle(element);
      document.body.appendChild(element);
    });

    it("should add checked stateful modifier class", function() {
      let event = new window.Event("click", { bubbles: true });
      element.dispatchEvent(event);
      expect(element.classList.contains("yi-toggle__checked")).toBe(true);
    });

I am getting the following error Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.

I expect to be able to dispatch a simple click event. My toggle component has a click event handler - it will remove a class and add a class

Aucun commentaire:

Enregistrer un commentaire