Jest.js 如何在react-testing-library中测试元素是否不可点击

lx0bsm1f  于 2023-08-01  发布在  Jest
关注(0)|答案(2)|浏览(163)

我有一个带有onClick处理程序的元素,可以通过将pointer-events: none添加到parent来禁用它(parent禁用children单击)。现在我想测试一下我的孩子是不能点击的,我该怎么做呢?使用userEvent.click抛出错误:

Error: Unable to perform pointer interaction as the element has `pointer-events: none`:

字符串
但这正是我想测试的...

z9smfwbn

z9smfwbn1#

您可以使用userEvent.clickpointerEventsCheck选项,它允许您控制执行指针事件检查的频率。
举例来说:

import { render, screen } from "@testing-library/react";
import userEvent, {
  PointerEventsCheckLevel,
} from "@testing-library/user-event";

test("child is not clickable when parent has pointer-events: none", () => {
  render(
    <div style={{ pointerEvents: "none" }}>
      <button onClick={() => console.log("clicked")}>Click me</button>
    </div>
  );
  const button = screen.getByRole("button", { name: /click me/i });

  userEvent.click(button, {
    pointerEventsCheck: PointerEventsCheckLevel.Never,
  });

  expect(console.log).not.toHaveBeenCalledWith("clicked");
});

字符串

vmjh9lq9

vmjh9lq92#

您可以使用expect().toThrow(),如这里所述。
根据您的测试设置,您还可以向onClick传递一个模拟函数,并Assert它永远不会被调用。

test('onClick is not called', () => {
    const mockFn = jest.fn();
    render(
        <Foo onClick={mockFn} />
    );

    // Add logic to prevent click and fire the event.

    expect(mockFn).not.toBeCalled();
});

字符串

相关问题