简体   繁体   English

存根和/或监视可选的全局函数:Sinon、mocha 和 chai

[英]Stubbing and/or spying on an optional global function: Sinon, mocha & chai

I have a method that checks whether or not a global function is defined (it may or may not be available, depends on each client's request).我有一个方法可以检查是否定义了全局函数(它可能可用也可能不可用,取决于每个客户的请求)。 If it is defined, it will call it with the appropriate data.如果已定义,它将使用适当的数据调用它。 If not, it will fail silently.如果没有,它将静默失败。 That's the desired behavior.这就是期望的行为。

What I want to do is test it.我想做的是测试它。 Is there a way to mock and/or spy on libFunction so that I can ensure it's being called once with the correct data (the function here is very much simplified, there's some data processing that happens along the way).有没有办法模拟和/或监视libFunction以便我可以确保使用正确的数据调用一次它(这里的函数非常简化,沿途会发生一些数据处理)。

Here's the method in question:这是有问题的方法:

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);
  }
}

I've tried defining libFunction in my tests and then stubbing that, but that doesn't do what I want:我已经尝试在我的测试中定义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;
  });
});

This test does not pass, however: AssertionError: expected undefined to be true但是,此测试未通过: AssertionError: expected undefined to be true

I've tried something similar with a spy:我用间谍尝试过类似的事情:

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;
  });
});

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

Is there a way to do this?有没有办法做到这一点?

FWIW, I came across this question while trying to solve an issue for stubbing a global method in Node. FWIW,我在尝试解决在 Node.js 中存根全局方法的问题时遇到了这个问题。 In my case, this worked (my example uses Sinon.sandbox , but "regular" Sinon.spy should work, as well):就我而言,这是有效的(我的示例使用Sinon.sandbox ,但“常规” Sinon.spy应该有效):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM