【发布时间】:2019-06-05 14:31:35
【问题描述】:
我在设置单元测试以确定使用正确参数调用函数时遇到问题。 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 和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。我在这里做错了什么还是错误地使用了任何一个工具?
【问题讨论】:
-
这间接解决了我有一段时间的一个问题。谢谢!
标签: jestjs react-hooks-testing-library