对和/或监视可选的全局函数:Sinn,mocha和chai

问题描述 投票:1回答:1

我有一种方法来检查是否定义了全局函数(取决于每个客户端的请求,该函数是否可用)。如果已定义,它将使用适当的数据进行调用。如果没有,它将静默失败。这是所需的行为。

我想做的就是测试它。有没有一种方法可以模拟和/或监视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

有没有办法做到这一点?

javascript testing mocha sinon chai
1个回答
0
投票

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

    const encodeSpy = sandbox.spy(global, "encodeURIComponent");
   // later...
   Sinon.assert.calledWith(encodeSpy, {expectedParamValue});
© www.soinside.com 2019 - 2024. All rights reserved.