我在设置单元测试以确定是否使用正确的参数调用函数时遇到问题。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
从未被调用过。我在这里做错了什么或者错误地使用了任一工具吗?
这行:
import * as myModule from './myModule.js'
...导入模块绑定myModule.js
into myModule
.
然后这一行:
const spy = jest.spyOn(myModule, 'bar');
...包裹着模块导出 for bar
在间谍...
...但是间谍永远不会被召唤,因为useAHook
不调用模块导出 for bar
,它只是调用bar
直接地。
如果你修改useAHook
调用模块导出bar
然后间谍就会被叫来。
有几种方法可以做到这一点。
你可以移动bar
进入它自己的模块...
...或者您可以导入模块绑定myModule.js
所以你可以调用模块导出bar
:
import { useCallback } from 'react';
import * as myModule from './myModule'; // <= import the module bindings
export const useAHook = (arg1, arg2) => {
const foo = useCallback(() => {
myModule.bar(arg1, arg2); // <= call the module export for bar
}, [arg1, arg2]);
return foo;
}
export const bar = (a, b) => {
//does some stuff with a and b
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)