我的间谍函数没有被调用——我怎样才能正确地监视这个函数?

My spy function is not getting called - how can I properly spy this function?

我正在尝试在我从单元测试调用的另一个函数中调用一个作为函数独立导入的函数。在这种情况下,如何在函数 IWantToSpy 上获得 1 的调用计数?

auditEvent.js:

const { verify } = require('@mycompany/verifylib');
const { functionIWantToSpy } = require('@mycompany/another-lib');

const auditEvent = () => {
  verify();
  functionIWantToSpy();
};

module.exports = { auditEvent };

测试:

const { verify } = require('@mycompany/verify-lib');
const { functionIWantToSpy } = require('@mycompany/another-lib');

describe('mytest', () => {

  let spiedFuntion;
  let verifyStub;

  beforeEach(() => {
    verifyStub = sinon.stub();
    ({auditEvent} = proxyquire('./auditEvent', {
      '@mycompny/verify-lib': {
        verify: verifyStub,
        '@noCallThru': true,
      },
    }));
    spiedFunction = sinon.spy(functionIWantToSpy);
  });

  it('should work'), async () => {

    auditEvent();
    expect(functionIWantToSpy).to.have.callCount(1);   // Getting callcount of 0 here...
  });
});

间谍涉及用新功能替换功能。您正在替换标识符 functionIWantToSpy 所引用的内容,以便它引用新的间谍函数,而不是 require('@mycompany/another-lib').functionIWantToSpy 所引用的原始函数。模块内的代码看不到您的新间谍功能。表达式 require('@mycompany/another-lib').functionIWantToSpy 引用原始函数,未更改。

因为 require caches results(即只有第一个 require("foo") 执行 foo,任何后续的 require("foo") 都会调用第一个 [=16= 返回的同一个对象]调用),可以修改require('@mycompany/another-lib')对象的functionIWantToSpy方法,使用sinon.spy:

的双参数形式
spiedFunction = sinon.spy(require('@mycompany/another-lib'), "functionIWantToSpy");

必须属性被测试的模块访问(和存储值)之前这样做:

verifyStub = sinon.stub();

// IMPORANT: FIRST, spy the functionIWantToSpy property on the required object before importing auditEvent
spiedFunction = sinon.spy(require('@mycompany/another-lib'), "functionIWantToSpy");

({auditEvent} = proxyquire('./auditEvent', {
  '@mycompny/verify-lib': {
    verify: verifyStub,
    '@noCallThru': true,
  },
}));

这应该可行,因为当 auditEvent 模块第一次运行并到达

const { functionIWantToSpy } = require('@mycompany/another-lib');

那么require('@mycompany/another-lib').functionIWantToSpy会提到间谍功能