无法执行dispatchevent' on EventTarget上:参数1不是类型' event'

发布于 2025-02-12 04:07:29 字数 1703 浏览 0 评论 0原文

我的测试代码从

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

但是由于某种原因,我从同一行的代码线上遇到此错误:

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

可执行演示: https: //codesandbox.io/s/busy-cache-xs3o2c

测试成功地抓住了一个按钮:< button onClick = {handleadd} testid =“ handleadd” =“ handleadd”> gt; gt; add and add&lt&lt>/butt&gt> gt; gt;

测试本身:

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);
  });
});

我已经从这篇文章,但在这种情况下不起作用。任何修复的想法都将不胜感激,谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文