【问题标题】:Jest spying on function called from within another开玩笑监视从另一个内部调用的函数
【发布时间】:2018-08-10 15:24:21
【问题描述】:

我有以下两个文件:

functions.js

function getOne() {
  return 1;
}

function getTen() {
  let val = 0;
  for (let x = 0; x < 10; x++) {
    val+= getOne();
  }
  return val;
}

module.exports = {
                  getOne,
                  getTen,
                 }

functions.test.js

const numberFunctions = require('../functions.js');
const getOne = numberFunctions.getOne;
const getTen = numberFunctions.getTen;

// passes
test('I should be able to get the number 1', () => {
  expect(getOne()).toBe(1);
});

describe('The getTen function', () => {
  // passes
  it('should return 10', () => {
    expect(getTen()).toBe(10);
  });

  // fails
  it('should call the getOne method 10 times', () => {
    const spy = jest.spyOn(numberFunctions, 'getOne');
    expect(spy).toHaveBeenCalledTimes(10);
  });
});

我正在尝试确保已从 getTen 函数中调用了函数 getOne。总共应该调用 10 次,但我的间谍总是声称它已被调用 0 次。

我尝试重新安排我的测试,以便将 getOne 函数模拟为全局函数,例如

it('should call the getOne method 10 times', () => {
    global.getOne = jest.fn(() => 1);
    expect(global.getOne).toHaveBeenCalledTimes(10);
  });

但这会导致相同的结果。如何监视从 getTen 函数中调用的 getOne 函数?

【问题讨论】:

  • 抢占 cmets:我知道,如果这是一个真实的例子,测试 getTen 的输出就足够了,而不是尝试询问它在内部做什么。如果getTen 的目的是简单地多次调用getOne 而不返回任何内容,我很想看看上述方法是否可行。

标签: jestjs


【解决方案1】:

我设法通过更改getTen 调用的getOne 函数来直接引用该函数导出的函数来实现此功能。否则,它似乎引用了一些内部作用域的函数,该函数不是被导出的,因此无法窥探。

这在this github conversation 中有更详细的解释,但要让我的测试按预期工作意味着我必须将我的代码重构为:

function getOne() {
  return 1;
}

function getTen() {
  let val = 0;
  for (let x = 0; x < 10; x++) {
    val+= module.exports.getOne(); // <-- this line changed
  }
  return val;
}

module.exports = {
                  getOne,
                  getTen,
                 }

现在,内部函数不是内部作用域,而是引用导出的函数并且可以被监视。

【讨论】:

    猜你喜欢
    • 2017-07-14
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 2020-05-21
    • 1970-01-01
    • 2021-10-09
    相关资源
    最近更新 更多