Jestjs 将react hooks测试库与jest.spyOn-spy一起使用不会被调用

Jestjs 将react hooks测试库与jest.spyOn-spy一起使用不会被调用,jestjs,react-hooks-testing-library,Jestjs,React Hooks Testing Library,我在设置单元测试以确定使用正确参数调用函数时遇到了一个问题useAHook返回调用函数bar的函数foo。代码如下所示 //myModule.js export const useAHook = (arg1, arg2) => { const foo = useCallback(() => { bar(arg1, arg2); }, [arg1, arg2]); return foo; } export const bar = (a, b) => {

我在设置单元测试以确定使用正确参数调用函数时遇到了一个问题
useAHook
返回调用函数
bar
的函数
foo
。代码如下所示

//myModule.js
export const useAHook = (arg1, arg2) => {
  const foo = useCallback(() => {
    bar(arg1, arg2);
  }, [arg1, arg2]);

  return foo;
}

export const bar = (a, b) => {
   //does some stuff with a and b
}
//myModule.spec.js

import * as myModule from './myModule.js'

it('should call foo with correct arguments', () => {
  const spy = jest.spyOn(myModule, 'bar');
  const { result } = renderHook(() => myModule.useAHook('blah', 1234));
  const useAHookFunc = result.current;

  useAHookFunc();

  // fails, spy is not called
  expect(spy).toBeCalledWith('blah', 1234);
});
我试图使用
renderHook
jest.spyOn
对这段代码进行单元测试。我想确认调用函数
foo
会导致使用正确的参数调用
bar
。我的单元测试是这样的

//myModule.js
export const useAHook = (arg1, arg2) => {
  const foo = useCallback(() => {
    bar(arg1, arg2);
  }, [arg1, arg2]);

  return foo;
}

export const bar = (a, b) => {
   //does some stuff with a and b
}
//myModule.spec.js

import * as myModule from './myModule.js'

it('should call foo with correct arguments', () => {
  const spy = jest.spyOn(myModule, 'bar');
  const { result } = renderHook(() => myModule.useAHook('blah', 1234));
  const useAHookFunc = result.current;

  useAHookFunc();

  // fails, spy is not called
  expect(spy).toBeCalledWith('blah', 1234);
});
结果是测试失败,表示从未调用
spy
。我是否在这里做错了什么,或者使用的工具不正确?

这一行:

import*作为myModule从'./myModule.js'导入
…将
myModule.js的模块绑定导入
myModule

那么这一行:

constspy=jest.spyOn(myModule,'bar');
…将
的模块导出包装在间谍中

…但是spy从未被调用,因为
useAHook
没有调用
bar
的模块导出,它只是直接调用
bar


如果修改
useAHook
以调用
bar
的模块导出,则会调用spy

有几种方法可以做到这一点

您可以将
移动到它自己的模块中

…或者您可以导入
myModule.js的模块绑定,以便调用
bar的模块导出

从'react'导入{useCallback};
从“/myModule”导入*作为myModule;//{
const foo=useCallback(()=>{
myModule.bar(arg1,arg2);//{
//用a和b做一些事情
}

这间接解决了我现在遇到的一个问题。谢谢!