【发布时间】:2021-01-02 04:58:26
【问题描述】:
我有一个获取异步函数并运行它的组件。
代码示例:
const Foo = ({func}) => {
const [val, setVal] = useState(null);
useEffect(()=> {
async function myAsyncFunf() {
const newVar = await func();
setVal(newVar)
};
myAsyncFunf();
},[]);
return <div>{val}</div>
}
it('test',async()=>{
const asyncMock = jest.fn().mockResolvedValue(43);
const props = {func: asyncMock}
const {getByText} = render(<Foo {...props}/>);
await wait(() => expect(asyncMock).toHaveBeenCalledTimes(1));
getByText('43');
});
测试失败并显示此消息:
控制台错误 警告:测试中对 Foo 的更新未包含在 act(...) 中。
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at
【问题讨论】:
标签: reactjs promise jestjs es6-promise react-testing-library