首页 > 解决方案 > 存根和/或监视可选的全局函数:Sinon、mocha 和 chai

问题描述

我有一个方法可以检查是否定义了全局函数(它可能可用也可能不可用,取决于每个客户的请求)。如果已定义,它将使用适当的数据调用它。如果没有,它将默默地失败。这是期望的行为。

我想做的是测试它。有没有一种方法可以模拟和/或监视,libFunction以便我可以确保使用正确的数据调用它一次(这里的函数非常简化,在此过程中会发生一些数据处理)。

这是有问题的方法:

function sendData(data) {
  let exists;
  try {
    // eslint-disable-next-line no-undef
    if (libFunction) exists = true;
  } catch (e) {
    exists = false;
  }
  if (exists) {
    // eslint-disable-next-line no-undef
    libFunction(data);
  }
}

我已经尝试libFunction在我的测试中进行定义,然后将其存根,但这并没有达到我想要的效果:

describe('sendEvent', function () {

  function libFunction(data) {
    console.log('hi', data);
  }

  it('should call libFunction once', function () {
    var stub = sinon.stub(libFunction);
    var data = "testing";
    sendEvent(data);
    expect(stub.called).to.be.true;
  });
});

但是,此测试未通过:AssertionError: expected undefined to be true

我用间谍尝试过类似的事情:

describe('sendEvent', function () {

  function libFunction(data) {
    console.log('hi', data);
  }

  it('should call libFunction once', function () {
    var spy = sinon.spy(libFunction);
    var data = "testing";
    sendEvent(data);
    expect(spy.called).to.be.true;
  });
});

这也失败了:AssertionError: expected false to be true

有没有办法做到这一点?

标签: javascripttestingmocha.jssinonchai

解决方案


FWIW,我在尝试解决在 Node.js 中存根全局方法的问题时遇到了这个问题。就我而言,这有效(我的示例使用Sinon.sandbox,但“常规”Sinon.spy也应该有效):

    const encodeSpy = sandbox.spy(global, "encodeURIComponent");
   // later...
   Sinon.assert.calledWith(encodeSpy, {expectedParamValue});

推荐阅读