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做一些事情
}
这间接解决了我现在遇到的一个问题。谢谢!