如何解决不得不重新查询元素以触发点击处理程序
我有一个测试,可以断言我的API请求提供了正确的参数。我正在使用MSW来模拟api,并且为请求处理程序提供了一个间谍:
test("supplies order direction descending if header button is clicked twice",async () => {
const mockHandler = jest.fn(handler);
server.use(rest.get(`${config.apiHost}/targets`,mockHandler));
// First request to /targets happens on render
render(<Route>{(props) => <TargetList history={props.history} />}</Route>);
const button = await screen.findByRole("button",{ name: "Port" });
// Second request to /targets happens on button click
userEvent.click(button);
await waitFor(() => {
expect(mockHandler).toHaveBeenCalledTimes(2);
});
// Third request to /targets SHOULD happen here but doesn't
userEvent.click(button);
await waitFor(() => {
expect(mockHandler).toHaveBeenCalledTimes(3);
const lastCall = mockHandler.mock.calls[2];
const requestArg = lastCall[0];
expect(requestArg.url.searchParams.get("orderby")).toBe("port");
expect(requestArg.url.searchParams.get("direction")).toBe("descending");
});
});
上面的代码不起作用,因为第二次在按钮上触发click事件似乎无济于事。但是,如果我重新查询该按钮,则可以成功触发处理程序:
test("supplies order direction descending if header button is clicked twice",async () => {
...
const button = await screen.findByRole("button",{ name: "Port" });
// Second request to /targets happens on b utton click
userEvent.click(button);
await waitFor(() => {
expect(mockHandler).toHaveBeenCalledTimes(2);
});
// Third request to /targets now works!
const button2 = await screen.findByRole("button",{ name: "Port" });
userEvent.click(button2);
await waitFor(() => {
expect(mockHandler).toHaveBeenCalledTimes(3); // SUCCESS!
...
});
});
为什么我必须重新查询相同的元素?我做错了什么吗?
解决方法
我没有完整的源代码,但是我认为您正在click事件处理程序上执行某些操作,这将迫使反应再次呈现,在那种情况下,旧元素将不再出现在DOM上,因此click事件处理程序将不会被调用。
P.S:您可以使用反应生命周期挂钩来确定是否重新渲染了组件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。