我有一个带有某种形式的屏幕,在提交时,我使用 axios 将请求发送到后端。成功收到响应后,我用 react-toastify 展示了一个 toast。非常直接的屏幕。但是,当我尝试使用 jest 和 react 测试库的集成测试来测试这种行为时,我似乎无法让 toast 出现在 DOM 上。
我有一个像这样的实用程序渲染器来渲染我正在使用 toast 容器测试的组件:
import {render} from "@testing-library/react";
import React from "react";
import {ToastContainer} from "react-toastify";
export const renderWithToastify = (component) => (
render(
<div>
{component}
<ToastContainer/>
</div>
)
);
在测试本身中,我使用 react-testing-library 填写表单,按下提交按钮,然后等待 toast 出现。我正在使用模拟服务人员来模拟响应。我确认响应返回正常,但由于某种原因,toast 拒绝出现。我目前的测试如下:
expect(await screen.findByRole("alert")).toBeInTheDocument();
我正在寻找具有角色警报的元素。但这似乎行不通。另外,我尝试做这样的事情:
...
beforeAll(() => {
jest.useFakeTimers();
}
...
it("test", () => {
...
act(() =>
jest.runAllTimers();
)
expect(await screen.findByRole("alert")).toBeInTheDocument();
}
我对 JS 有点陌生,问题可能是由于 axios 和 react-toastify 的异步性质,但我不知道如何测试这种行为。我尝试了很多东西,包括模拟计时器并运行它们,模拟计时器并推进它们,不模拟它们并等待等。我什至尝试模拟 toast 的调用,但我无法让它正常工作。另外,这似乎是一个实现细节,所以我认为我不应该嘲笑它。
我认为问题是我在 axios 承诺解决后显示敬酒,所以计时器不知何故感到困惑。
我试图搜索很多地方,但未能找到答案。
提前致谢。