【发布时间】:2021-08-03 18:05:51
【问题描述】:
我想 JEST 测试一个 React 组件,它在渲染状态之前和之后都会在超时后更新状态。 expect() 断言在 test() 中工作正常,但在 SetTimeout 回调中使用时会中断。在 setTimeout 回调中未定义期望的错误状态。
我在这里创建了一个沙盒: https://codesandbox.io/s/jest-delayed-render-test-j5b7l
SetTimeout 后的简单组件更新状态。
// delayed.js
import { useEffect, useState } from "react";
export const Delayed = () => {
let [value, setValue] = useState("foo");
useEffect(() => {
let handle = setTimeout(() => {
setValue("bar");
}, 3000);
return () => {
clearTimeout(handle);
};
}, []);
return (
<>
<h1>MyPromise</h1>
<p>value = {value}</p>
</>
);
};
简单的测试断言组件之前和更新超时
// delayed.test.js
import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import { Delayed } from "./delayed";
let container = null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
unmountComponentAtNode(container);
container.remove();
container = null;
});
it("checks initial value", async () => {
await act(async () => {
render(<Delayed />, container);
});
expect(container.textContent).toContain("foo");
});
it("checks final value", async () => {
await act(async () => {
render(<Delayed />, container);
});
setTimeout(() => {
// this doesnt get executed!
// error: expect is not defined
expect(container.textContent).toContain("1234");
}, 2000);
});
【问题讨论】:
标签: reactjs asynchronous jestjs settimeout