如何在开玩笑中测试呼叫和应用功能?

时间:2018-01-24 16:20:00

标签: javascript jest

这是 callnapply.js 文件

Access-Control-Allow-...

这是测试文件中包含非工作测试的片段:

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); }); 实际上是否仅由method函数调用?我想检查是否正在调用Function.prototype.call,而不是为.call()调用编写的其他实现。

1 个答案:

答案 0 :(得分:3)

您可以模拟.call()方法本身:

const outer = function() {}
outer.call = jest.fn()

然后你可以在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);
});

请参阅this working REPL