React hooks testing library 如何使用useEffect/setState挂钩

React hooks testing library 如何使用useEffect/setState挂钩,react-hooks-testing-library,React Hooks Testing Library,我无法通过以下测试: 从“react”导入{useffect,useState}; 导出函数useComponentResources(必需){ 常量[componentResources,setComponentResources]=useState(null); useffect(()=>{ 如果(需要){ //api调用 setTimeout(()=>setComponentResources({}),100; } },[必需]; 返回组件资源; } 从“@testing library

我无法通过以下测试:

从“react”导入{useffect,useState};
导出函数useComponentResources(必需){
常量[componentResources,setComponentResources]=useState(null);
useffect(()=>{
如果(需要){
//api调用
setTimeout(()=>setComponentResources({}),100;
}
},[必需];
返回组件资源;
}
从“@testing library/react hooks”导入{renderHook};
从“/component resources.hook”导入{useComponentResources}”;
描述(“组件资源.hook”,()=>{
它(“在需要时获取资源”,()=>{
//表演
const{result}=renderHook(()=>useComponentResources(true));
//断言
expect(result.current).toEqual({});
});
});
它不断失败:

expect(received).toEqual(expected)

Expected value to equal:
  {}
Received:
  null

Difference:

  Comparing two different types of values. Expected object but received null.

   7 |     const { result } = renderHook(() => useComponentResources(true));
   9 |     //assert
> 10 |     expect(result.current).toEqual({});
  11 |   });
  12 | });
我在codesandbox中创建了一个复制案例:


renderHook
不会等待您的
设置超时启动;它不知道你的组件有什么“副作用”。因此,当运行
expect()
时,当前值仍然是其默认值-
null

我们可以使用
waitForNextUpdate
强制测试等待钩子再次更新,它位于对象
renderHook
返回的位置
waitForNextUpdate
是一个函数,它返回一个承诺,一旦钩子再次更新(例如,当setTimeout触发时),该承诺就会得到解决


您的回答完全有道理,但仍然无法运行。你能通过我共享的codesandbox中的测试吗?因此,如果我只使用
wait waitForNextUpdate()
,它就起作用了。如果你更新你的答案,我会把它标记为接受。
import { renderHook } from "@testing-library/react-hooks";
import { useComponentResources } from "./component-resources.hook";

describe("component-resources.hook", () => {
  it("fetches resources when required", async () => {
    const { result, waitForNextUpdate } = renderHook(() => useComponentResources(true));

    await waitForNextUpdate();

    expect(result.current).toEqual({});
  });
});