英文:
How to test if element is not clickable in react-testing-library
问题
我有一个具有onClick
处理程序的元素,可以通过在父元素上添加pointer-events: none
来禁用它(父元素禁用子元素的点击)。
现在我想测试我的子元素是否不可点击,我该怎么做?
使用userEvent.click
会引发错误:
错误:无法执行指针交互,因为元素具有`pointer-events: none`:
但这正是我想要测试的内容...
英文:
I have an element with an onClick
handler which may be disabled by adding pointer-events: none
to parent (parent disables children click).
Now I want to test that my child is not clickable, how can I do this?
Using userEvent.click
throws error:
Error: Unable to perform pointer interaction as the element has `pointer-events: none`:
But this is exactly what I am trying to test...
答案1
得分: 4
你可以使用userEvent.click
的pointerEventsCheck
选项,它允许你控制指针事件检查的频率。
例如:
import { render, screen } from "@testing-library/react";
import userEvent, {
PointerEventsCheckLevel,
} from "@testing-library/user-event";
test("当父元素有pointer-events: none时,子元素不可点击", () => {
render(
<div style={{ pointerEvents: "none" }}>
<button onClick={() => console.log("clicked")}>点击我</button>
</div>
);
const button = screen.getByRole("button", { name: /点击我/i });
userEvent.click(button, {
pointerEventsCheck: PointerEventsCheckLevel.Never,
});
expect(console.log).not.toHaveBeenCalledWith("clicked");
});
英文:
You can use the pointerEventsCheck
option of userEvent.click
, which allows you to control how often the pointer events check is performed.
For example:
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");
});
答案2
得分: 0
你可以使用 expect().toThrow()
,如文档中所述 here。
根据你的测试设置,你还可以传递一个模拟函数给你的 onClick
,并断言它从未被调用。
test('onClick is not called', () => {
const mockFn = jest.fn();
render(
<Foo onClick={mockFn} />
);
// 添加阻止点击并触发事件的逻辑。
expect(mockFn).not.toBeCalled();
});
英文:
You could use expect().toThrow()
as documented here.
Depending on your test setup, you could also pass your onClick
a mocked function and assert that it is never called.
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();
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论