我创建了2个辅助函数,其中一个也是第一个的快捷方式,在我的测试中,我想验证是否调用了该函数,这些函数位于同一文件中:
export function test1(param1, param2, param3, param4) {
return { param1, param2, ...(param3 && { param3 }), ...(param4 && { param4 }) };
}
export function test2(param1, param2) {
return test1(param1, null, null, param2);
}
在测试中,我需要证明第一个被第二个调用:
import * as Util from './my-util-file';
const test2 = Util.test2;
...
it('should call test1 when test2 is called', () => {
const test1 = spyOn(Util, 'test1').and.callThrough();
test2('test', 1);
expect(test1).toHaveBeenCalledWith('test', null, null, 1);
});
或
import {test1, test2} from './my-util-file';
...
it('should call test1 when test2 is called', () => {
const test1Spy = jasmine.createSpy('test1');
test2('test', 1);
expect(test1Spy).toHaveBeenCalledWith('test', null, null, 1);
});
或
import * as Util from './my-util-file';
const test2 = Util.test2;
...
it('should call test1 when test2 is called', () => {
const test1Spy = spyOnProperty(Util, 'test1');
test2('test', 1);
expect(test1Spy).toHaveBeenCalledWith('test', null, null, 1);
});
或
import {test1, test2} from './my-util-file';
...
it('should call test1 when test2 is called', () => {
const test1Spy = spyOn(window as any, 'test1');
test2('test', 1);
expect(test1Spy).toHaveBeenCalledWith('test', null, null, 1);
});
但是问题是我得到了错误:
预期已调用间谍test1。
答案 0 :(得分:1)
这不是茉莉花的问题。这就是javascript模块在编译/编译时的行为。
var test1 = function test1() {};
var test2 = function test2() { test1(); };
exports.test1 = test1;
exports.test2 = test2;
声明函数test2
时,对test1
函数的引用将包含在函数声明中。但是在规范中,我们真正要导入的是exports.test1
&& exports.test2
。因此,基本上,我们在监视不想要的东西,例如exports.test1
。
因此,为了保留参考,我们可以定义和导出测试函数,如下所示:
const test1 = function(param1: any, param2: any, param3: any, param4: any) {
return {
param1,
param2,
...(param3 && { param3 }),
...(param4 && { param4 })
};
};
const test2 = function(param1: any, param2: any) {
return testFunctions.test1(param1, null, null, param2); //Here we are attaching the refernce
};
export const testFunctions = {
test1,
test2
};
我们可以如下进行测试:
import * as test from './test';
const functions = test.testFunctions;
it('should call test1 when test2 is called', () => {
const test1 = spyOn(functions, 'test1').and.callThrough();
functions.test2('test', 1);
expect(test1).toHaveBeenCalledWith('test', null, null, 1);
});
一个不错的article,它解释了上述问题,供您参考