【发布时间】:2019-03-03 14:04:46
【问题描述】:
如何使用模拟来计算通过call 或apply 进行的函数调用
// mylib.js
module.exports = {
requestInfo: function(model, id) {
return `The information for ${model} with ID ${id} is foobar`;
},
execute: function(name) {
return this[name] && this[name].apply(this, [].slice.call(arguments, 1));
},
};
// mylib.test.js
jest.mock('./mylib.js');
var myLib = require('./mylib.js');
test('', () => {
myLib.execute('requestInfo', 'Ferrari', '14523');
expect(myLib.execute.mock.calls.length).toBe(1); // Success!
expect(myLib.requestInfo.mock.calls.length).toBe(1); // FAIL
});
如果我显式调用myLib.requestInfo,则第二个期望成功。
有没有办法观察通过apply 或call 调用函数的模块模拟调用?
【问题讨论】:
-
在您的示例中,
myLib没有arrangeViewing方法。您能否更新示例,否则很难得到您正在尝试的内容。 -
对不起,我从示例中删除了错误的方法。已更新。
标签: javascript unit-testing mocking jestjs