【问题标题】:Stubbing and/or spying on an optional global function: Sinon, mocha & chai存根和/或监视可选的全局函数:Sinon、mocha 和 chai
【发布时间】:2019-07-27 12:25:10
【问题描述】:

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

我想做的是测试它。有没有办法模拟和/或监视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

有没有办法做到这一点?

【问题讨论】:

  • 你可能想要sinon.spy(window, 'libFunction'),你正在做的是创建一个由libFunction 支持的间谍,而不是libFunction 的间谍。
  • window 没有定义,因为我没有在我的测试环境中模拟浏览器。还有其他方法吗?
  • 你可以试试global而不是window

标签: javascript testing mocha.js sinon chai


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-01
    • 2019-06-05
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 2016-08-04
    相关资源
    最近更新 更多