我如何测试玩笑和应用功能? [英] How do I test call and apply functions in jest?
本文介绍了我如何测试玩笑和应用功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的 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;
这是测试文件的片段,其中包含无效的测试:
And here's a snippet from the test file which contains the non-working test:
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);
});
如何编写测试以检查我通过的method
实际上是否仅由Function.prototype.call
函数调用?我想检查是否正在调用.call()
,而不是为method
调用编写的其他实现.
How do I write the test to check if the method
that I am passing is, in fact, being called by the Function.prototype.call
function only? I want to check whether .call()
is being called and not some other implementation that has been written for the method
call.
推荐答案
您可以模拟.call()
方法本身:
const outer = function() {}
outer.call = jest.fn()
然后,您可以在outer.call
上进行常规的笑话模拟测试.
Then you can do usual jest mock tests on outer.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);
});
请参见此有效的REPL .
这篇关于我如何测试玩笑和应用功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文