【问题标题】:Why can't I properly stub the twilio library with sinon?为什么我不能用 sinon 正确地存根 twilio 库?
【发布时间】:2019-03-13 12:27:02
【问题描述】:

在我的代码中,我有:

function handleMessage() {
  const twilio = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
  let recordings = twilio.recordings(foundConference.RecordingSid);
  console.log('recordings', recordings);
  return recordings.remove();
}

在我的存根中,我有:

const sinon = require('sinon');
const twilio = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);

exports.twilioRecordings = () => {
  console.log('about to stub', twilio.recordings);
  sinon.stub(twilio, 'recordings').returns('here');
  console.log('finished stub', twilio.recordings);

  return;
};

但是,它实际上并没有创建存根函数。它仍在使用原始的recordings 函数。我做错了什么?

【问题讨论】:

  • 你是如何尝试使用存根的?
  • 在我的handleMessage 函数中,我有` let recordings = twilio.recordings(foundConference.RecordingSid);`
  • 我明白了,我的意思是你是怎么把测试文件放在一起来使用存根的?

标签: node.js mocking twilio sinon


【解决方案1】:

Twilio npm package returns a function which creates a new object on every call,它是not a singleton。因此,您的存根 twilio 实例仅适用于测试。

还有twilio.recordings(与所有其他属性一样)is defined through the getter function in prototype,所以它们是read only:

Object.defineProperty(Twilio.prototype,
  'recordings', {
  get: function() {
    return this.api.account.recordings;
  }
});

因此,存根实际的 twilio 实例无效。除非你 change the instance's prototype,但我认为只进行单元测试不值得。

我建议您重构代码以将 twilio 初始化放入单独的方法中:

function getTwilio() {
   return require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
}

接下来您的hangleMessage 将如下所示:

function handleMessage() {
  const twilio = this.getTwilio();
  const recordings = twilio.recordings(...);
  ...
}

接下来,在您的测试中,您可以存根 getTwilio() 以返回存根:

const twilioStub = {
    recordings: sinon.stub(),
    remove: sinon.stub()
}
sinon.stub(myAwesomeModule, 'getTwilio').returns(twilioStub);

你也可以考虑使用mock-require包:

const sinon = require('sinon');
const mock = require('mock-require');
mock('twilio', () => ({
  recordings: sinon.stub(),
}));

这里is a question about how-to mock dependencies,可能还有其他有用的库来存根所需的模块。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2017-09-30
    • 2017-03-25
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    相关资源
    最近更新 更多