【发布时间】:2018-08-10 15:24:21
【问题描述】:
我有以下两个文件:
functions.js
function getOne() {
return 1;
}
function getTen() {
let val = 0;
for (let x = 0; x < 10; x++) {
val+= getOne();
}
return val;
}
module.exports = {
getOne,
getTen,
}
functions.test.js
const numberFunctions = require('../functions.js');
const getOne = numberFunctions.getOne;
const getTen = numberFunctions.getTen;
// passes
test('I should be able to get the number 1', () => {
expect(getOne()).toBe(1);
});
describe('The getTen function', () => {
// passes
it('should return 10', () => {
expect(getTen()).toBe(10);
});
// fails
it('should call the getOne method 10 times', () => {
const spy = jest.spyOn(numberFunctions, 'getOne');
expect(spy).toHaveBeenCalledTimes(10);
});
});
我正在尝试确保已从 getTen 函数中调用了函数 getOne。总共应该调用 10 次,但我的间谍总是声称它已被调用 0 次。
我尝试重新安排我的测试,以便将 getOne 函数模拟为全局函数,例如
it('should call the getOne method 10 times', () => {
global.getOne = jest.fn(() => 1);
expect(global.getOne).toHaveBeenCalledTimes(10);
});
但这会导致相同的结果。如何监视从 getTen 函数中调用的 getOne 函数?
【问题讨论】:
-
抢占 cmets:我知道,如果这是一个真实的例子,测试
getTen的输出就足够了,而不是尝试询问它在内部做什么。如果getTen的目的是简单地多次调用getOne而不返回任何内容,我很想看看上述方法是否可行。
标签: jestjs