我在设置单元测试以确定使用正确参数调用函数时遇到问题。useAHook
返回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
}
我正在尝试使用renderHook
and对这段代码进行单元测试jest.spyOn
。我想确认调用函数foo
会导致bar
使用正确的参数被调用。我的单元测试看起来像这样
//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
永远不会被调用。我在这里做错了什么还是错误地使用了任何一个工具?