这是我的callnapply.js文件
const callAndApply = {
caller(object, method, nameArg, ageArg, tShirtSizeArg) {
method.call(object, nameArg, ageArg, tShirtSizeArg);
},
applier(object, method, argumentsArr) {
method.apply(object, argumentsArr);
},
};
module.exports = callAndApply;
这是测试文件的片段,其中包含无效的测试:
const callnapply = require('./callnapply');
test('testing Function.prototype.call as mock function', () => {
const outer = jest.fn();
const name = 'Aakash';
const age = 22;
const tee = 'M';
callnapply.caller(this, outer, name, age, tee);
expect(outer.call).toHaveBeenCalledWith(name, age, tee);
});
如何编写测试以检查我传递的方法是否实际上仅由Function.prototype.call函数调用?我想检查.call()是否被调用,而不是为方法调用编写的其他实现.
解决方法:
您可以模拟.call()方法本身:
const outer = function() {}
outer.call = jest.fn()
然后,您可以对external.call进行通常的笑话模拟测试.
这是工作测试文件:
const callnapply = require('./callnapply');
test('testing Function.prototype.call as mock function', () => {
const outer = function() {};
outer.call = jest.fn();
const name = 'Aakash';
const age = 22;
const tee = 'M';
callnapply.caller(this, outer, name, age, tee);
expect(outer.call).toHaveBeenCalledWith(this, name, age, tee);
});