【问题标题】:Jest: how to count call from mock methods called via `call` or `apply`?开玩笑:如何计算通过“call”或“apply”调用的模拟方法的调用?
【发布时间】:2019-03-03 14:04:46
【问题描述】:

如何使用模拟来计算通过callapply 进行的函数调用

// 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,则第二个期望成功。

有没有办法观察通过applycall 调用函数的模块模拟​​调用?

【问题讨论】:

  • 在您的示例中,myLib 没有 arrangeViewing 方法。您能否更新示例,否则很难得到您正在尝试的内容。
  • 对不起,我从示例中删除了错误的方法。已更新。

标签: javascript unit-testing mocking jestjs


【解决方案1】:

来自jest.mockdoc

在需要时使用自动模拟版本模拟模块。

可以通过更好地描述“自动模拟版本”的含义来改进文档,但实际情况是 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
});

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 2020-03-15
    • 2018-07-30
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    相关资源
    最近更新 更多