如何使用模拟来计算通过 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
调用其函数的模块模拟调用?
最佳答案
来自jest.mock
doc :
Mocks a module with an auto-mocked version when it is being required.
文档可能可以通过更好地描述“自动模拟版本”的含义来改进,但发生的情况是,Jest
保持模块的 API 表面相同,同时将实现替换为空mock functions .
因此,在这种情况下,execute
被调用,但它已被空的模拟函数替换,因此 requestInfo
永远不会被调用,从而导致测试失败。
为了保持 execute
的实现完整,您需要避免自动模拟整个模块,而是使用 jest.spyOn
之类的东西来监视原始函数。 :
var myLib = require('./mylib.js');
test('', () => {
jest.spyOn(myLib, 'execute'); // spy on execute
jest.spyOn(myLib, 'requestInfo') // spy on requestInfo...
.mockImplementation(() => {}); // ...and optionally replace the implementation
myLib.execute('requestInfo', 'Ferrari', '14523');
expect(myLib.execute.mock.calls.length).toBe(1); // SUCCESS
expect(myLib.requestInfo.mock.calls.length).toBe(1); // SUCCESS
});
关于javascript - 开 Jest : how to count call from mock methods called via `call` or `apply` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54969622/