【问题标题】:Sinon - How to stub authentication library (Authy -Twilio)Sinon - 如何存根身份验证库 (Authy -Twilio)
【发布时间】:2017-03-25 07:54:10
【问题描述】:

我目前是Sinon、Mocha、Supertest 的新手,正在编写测试。在我当前的场景中,我有验证我的“OTP”的身份验证库,并在验证后继续在回调函数中执行操作。

我无法模拟回调以返回 null 并继续测试其余代码。以下是我的代码 sn-p:

Controller.js


var authy = require('authy')(sails.config.authy.token);
 authy.verify(req.param('aid'), req.param('oid'), function(err, response) {
  console.log(err);
  if (err) {
    return res.badRequest('verification failed.');
  }
....

我的测试是:

 var authy = require('authy')('token');



describe('Controller', function() {
  before(function() {
    var authyStub = sinon.stub(authy, 'verify');
    authyStub.callsArgWith(2, null, true);
  });

  it('creates a test user', function(done) {
    // This function will create a user again and again.
    this.timeout(15000);
    api.post('my_endpoint')
      .send({
        aid: 1,
        oid: 1
      })
      .expect(201, done);


  });
});

我本质上想在回调中调用 authy verify get a null 作为“err”,这样我就可以测试其余的代码。

任何帮助将不胜感激。 谢谢

【问题讨论】:

  • @philnash,你能告诉我如何模拟 authy 验证

标签: javascript twilio sinon supertest authy


【解决方案1】:

问题在于您在测试和代码中使用了 authy 对象的不同实例。见这里authy github repo。

在你的代码中

var authy = require('authy')(sails.config.authy.token);

在你的测试中

var authy = require('authy')('token');

所以你的存根通常没问题,但它永远不会像这样工作,因为你的代码不使用你的存根。

一种方法是允许从外部注入控制器中的authy 实例。像这样的:

function Controller(authy) {
    // instantiate authy if no argument passed

在你的测试中你可以这样做

describe('Controller', function() {
    before(function() {
        var authyStub = sinon.stub(authy, 'verify');
        authyStub.callsArgWith(2, null, true);
        // get a controller instance, however you do it
        // but pass in your stub explicitly
        ctrl = Controller(authyStub);
    });
});

【讨论】:

  • 感谢@nomve 的回复!一段时间以来,我一直对此感到头疼。你如何将参数传递给“控制器”。由于目前我正在调用“创建”函数,例如。 module.exports{ create: function(req, res, next) { .....
  • 我不知道你的 controller.js 文件长什么样。不管它看起来如何,无论使用 authy 的代码看起来如何,您都需要在其中传递您的存根实例。否则你不能真正地存根它。
猜你喜欢
  • 2016-02-24
  • 2019-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
相关资源
最近更新 更多