Sinon - 如何存根认证库(Authy -Twilio)

时间:2016-11-11 05:58:44

标签: javascript twilio sinon supertest authy

我目前是Sinon,Mocha,Supertest的新手,也是编写测试的过程。在我目前的情况下,我有验证库来验证我的" OTP"并且在验证之后继续在回调函数内进行操作。

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

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验证获取null为"错误"在回调中,所以我可以测试其余的代码。

任何帮助都将受到高度赞赏。 感谢

1 个答案:

答案 0 :(得分:0)

问题是您在测试和代码中使用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);
    });
});