1

My test code emulates a test with the same line of code from the docs:

button.dispatchEvent(new MouseEvent("click", { bubbles: true }));

But for some reason I'm getting this error from the same line of code:

Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.

Executable Demo: https://codesandbox.io/s/busy-cache-xs3o2c

There is a button successfully grabbed by the test: <button onClick={handleAdd} testid="handleAdd">Add</button>

The test itself:

let container;

describe("Testing Buttons", () => {
  beforeEach(() => {
    container = document.createElement("div");
    document.body.appendChild(container);
  });

  afterEach(() => {
    document.body.removeChild(container);
    container = null;
  });

  it("should increment", () => {
    act(() => {
      ReactDOM.createRoot(container).render(<App />);
    });

    let h1 = screen.getByRole("heading", { level: 1 });
    let count = Number(h1.innerHTML);
    expect(count).toBe(0);
    const button = screen.getByText("Add");
    expect(button).toBeInTheDocument();
    act(() => {
      button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
    }); // why bug?s literally the same as here: https://reactjs.org/docs/test-utils.html#act
    expect(count).toBe(1);
  });
});

I've tried this code from this post but does not work for this case. Any ideas of fixes would be appreciated, thank you.

user8758206
  • 2,106
  • 4
  • 22
  • 45

0 Answers0