NodeJS 中带有 sinon 的 Spy module.exports 函数总是返回 0

问题描述

我正在尝试使用用 Sinon 编写的测试用例跟踪对另一个函数调用次数我有以下代码,在运行测试时,calledFuncSpy callCount 总是让我得到 0,这是意料之外的。同时,在 console.log 上运行另一个间谍给了我正确的输出,我在代码中留下了注释。有谁知道可能是什么问题?

这是代码。如果需要更多信息来解决此问题,请告诉我。

specs/mymodule.js

const mymodule = require("../src/mymodule.js");
var sinon = require("sinon");
const assert = require("assert");



describe("Test suite",function() {
  let calledFuncSpy;
  let consoleSpy;

  beforeEach(function () {
    calledFuncSpy = sinon.spy(mymodule,"calledFunc");
    consoleSpy = sinon.spy(console,"log");
  })
  afterEach(function () {
    calledFuncSpy.restore();
    consoleSpy.restore();
  })

  it("Test the add method",function () {
    mymodule.ownHelloWorld();
    assert.deepStrictEqual(calledFuncSpy.callCount,1);
    // assert.deepStrictEqual(consoleSpy.callCount,1);
  });
})

src/mymodule.js

function ownHelloWorld() {
  calledFunc();
}

function calledFunc() {
  console.log("Hello world");
}

module.exports = {
  ownHelloWorld,calledFunc
}

解决方法

calledFunc 函数内调用的

ownHelloWorld 不能被存根。它将始终使用原始的 calledFunc 函数。 sinon.spy(mymodule,"calledFunc") 在调用 ownHelloWorld 函数时不能修改它的引用。另外,请参阅此 comment

你可以像这样重构它:

mymodule.js

function ownHelloWorld() {
  module.exports.calledFunc();
}

function calledFunc() {
  console.log('Hello world');
}

module.exports = {
  ownHelloWorld,calledFunc,};

mymodule.test.js

const mymodule = require('./mymodule');
var sinon = require('sinon');

describe('Test suite',function () {
  let calledFuncSpy;
  let consoleSpy;

  beforeEach(function () {
    calledFuncSpy = sinon.spy(mymodule,'calledFunc');
    consoleSpy = sinon.spy(console,'log');
  });
  afterEach(function () {
    calledFuncSpy.restore();
    consoleSpy.restore();
  });

  it('Test the add method',function () {
    mymodule.ownHelloWorld();
    sinon.assert.calledOnce(calledFuncSpy);
  });
});

测试结果:

  Test suite
Hello world
    ✓ Test the add method


  1 passing (5ms)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |      100 |     100 |     100 |                   
 mymodule.js |     100 |      100 |     100 |     100 |                   
-------------|---------|----------|---------|---------|-------------------

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...