【发布时间】:2020-11-06 16:43:42
【问题描述】:
重新排序以下测试将使find one after the other 测试通过。
另一种让它通过的方法是让should be able to find 3 directly 测试通过,例如,让它找到2 而不是3。
describe("Counter", () => {
test("should be able to find 3 directly", async () => {
render(<Counter />);
const three = await waitFor(() => screen.findByText(/3/i));
expect(three).toBeInTheDocument();
});
test("find one after the other", async () => {
render(<Counter />);
const one = await waitFor(() => screen.findByText(/1/i));
expect(one).toBeInTheDocument();
const two = await waitFor(() => screen.findByText(/2/i));
expect(two).toBeInTheDocument();
const three = await waitFor(() => screen.findByText(/3/i));
expect(three).toBeInTheDocument();
});
});
所以问题是,为什么测试的顺序很重要?为什么clean up 不起作用?
【问题讨论】:
-
Counter正在使用setInterval所以第二个测试通过基本上是幸运的。通常任何取决于特定日期/时间的测试,无论是否反应,您都可以使用fake timers 来指定/控制时间增量。对于计数器,您将设置假计时器,然后将时间更新为 3 秒后,以便您可以检查文本3是否出现。此外,您可能没有在组件useInterval 中正确使用 setInterval。 -
我要补充一点,虽然有反应测试库方法可以等待文本出现,但假计时器是在 jest、mocha、tape 或任何其他库中如何控制时钟以确保事情正在按照您期望的方式出现/执行。
标签: reactjs unit-testing jestjs react-testing-library