如何解决使用带有mockResolvedValue的异步功能测试React组件-承诺未解决
我有一个获取异步功能并运行它的组件。
代码示例:
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');
});
测试失败,并显示以下消息:
console.error 警告:测试中对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
解决方法
在组件中,func实际上与道具有关,您只是将其命名为“ func”
您需要对其进行重构以访问func或显式访问对象的属性。
选项1 -销毁。注意花括号“ {func}”
const Foo = ({func}) => {
const [val,setVal] = useState(null);
useEffect(()=> {
async function myAsyncFunf() {
const newVar = await func();
setVal(newVar)
};
myAsyncFunf();
},[]);
return <div>{val}</div>
}
选项2 -访问“道具”的属性“ func”
const Foo = (props) => {
const [val,setVal] = useState(null);
useEffect(()=> {
async function myAsyncFunf() {
const newVar = await props.func();
setVal(newVar)
};
myAsyncFunf();
},[]);
return <div>{val}</div>
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。