如何模拟反应自定义钩子返回值? [英] How to mock react custom hook returned value?

查看:32
本文介绍了如何模拟反应自定义钩子返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的自定义钩子:

  export function useClientRect() {
    const [scrollH, setScrollH] = useState(0);
    const [clientH, setClientH] = useState(0);
    const ref = useCallback(node => {
      if (node !== null) {
        setScrollH(node.scrollHeight);
        setClientH(node.clientHeight);
      }
    }, []);
    return [scrollH, clientH, ref];
  }
}

我希望每次调用它时,它都返回我的值.喜欢:

I want each time that it is called, it return my values. like:

jest.mock('useClientRect', () => [300, 200, () => {}]);

我怎样才能做到这一点?

How can I achieve this?

推荐答案

将钩子作为模块加载.然后模拟模块:

Load the hook as a module. Then mock the module:

jest.mock('module_name', () => ({
    useClientRect: () => [300, 200, jest.fn()]
}));

应在 test fn 之外的文件顶部调用模拟.因此,我们将只有一个数组作为模拟值.

mock should be called on top of the file outside test fn. Therefore we are going to have only one array as the mocked value.

如果你想在不同的测试中用不同的值模拟钩子:

If you want to mock the hook with different values in different tests:

import * as hooks from 'module_name';

it('a test', () => {
    jest.spyOn(hooks, 'useClientRect').mockImplementation(() => ([100, 200, jest.fn()]));
    //rest of the test
});

这篇关于如何模拟反应自定义钩子返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆