【问题标题】:get renderHook's result more than once多次获取renderHook的结果
【发布时间】:2019-12-25 13:23:01
【问题描述】:

我得到了一个测试,它像这样调用renderHook

const { result } = renderHook(() => useMyHook(useDispatch()), wrapper);

一切正常,工作正常,我可以在result.current..中得到返回值。

似乎我不能用renderHook 调用另一个钩子。如果我做同样的事情,那么它说result 已经定义。如果我将名称更改为其他名称,例如“res”,则表示 res 未定义,就像它仅适用于特定名称“result”。

那我怎么能调用不止一次呢?

【问题讨论】:

    标签: reactjs react-testing-library


    【解决方案1】:

    由于您应该每次测试只测试一个钩子,也许您必须先卸载当前组件:

    const { result, unmount } = renderHook(() => useMyHook(useDispatch()), wrapper);
    
    // ... do what you need with result
    
    unmount();
    
    // call your new hook...
    const { result } = renderHook(() => useNewHook(useDispatch()), wrapper);
    

    【讨论】:

    • 尝试清理而不是卸载
    【解决方案2】:

    我可能不在,但看起来你正在调用这样的东西:

    const { result } = renderHook(() => useMyHook(useDispatch()), wrapper);
    const { result } = renderHook(() => useMyHook(useDispatch()), wrapper);
    

    在这种情况下,您正在尝试重新定义变量 result

    你可以这样定义它:

    {
      // 1st time
      const { result } = renderHook(() => useMyHook(useDispatch()), wrapper);
      // validate result of creating 1st hook in here
    }
    {
      // 2nd time
      const { result } = renderHook(() => useMyHook(useDispatch()), wrapper);
      // validate result of creating 2nd hook in here
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-17
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 2013-04-13
      • 1970-01-01
      相关资源
      最近更新 更多