javascript - 开 Jest : how to count call from mock methods called via `call` or `apply` ?

标签 javascript unit-testing mocking jestjs

如何使用模拟来计算通过 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 调用其函数的模块模拟​​调用?

最佳答案

来自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/

相关文章:

javascript - CSS - 你可能需要一个合适的加载器来处理这种文件类型

javascript - 使用 BreezeJS 获取 DateTime 类型的日期

java - 如何在不使用 "add"等的情况下在 DAO 中测试 "find"?

c# - 如何在 C# 中实现锁并对其进行单元测试

android - Roboguice 和模拟 : How to have roboguice inject a mock service when testing but use the REAL otherwise?

javascript - 通过javascript添加Google Analytics(分析)注释

javascript - D3.js - 无法读取未定义的属性 'axis'

scala - 使用 Akka TestProbe 断言收到的消息顺序

unit-testing - 行为与基于状态的测试

Python 模拟具有不同结果的多个调用