Sinon-如何存根身份验证库(Authy -Twilio) [英] Sinon - How to stub authentication library (Authy -Twilio)

查看:166
本文介绍了Sinon-如何存根身份验证库(Authy -Twilio)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前是Sinon,Mocha,Supertest的新手,并且正在编写测试.在当前情况下,我具有身份验证库,该库可验证我的"OTP",并在验证后继续执行回调函数中的操作.

I am currently new to Sinon, Mocha, Supertest and in the process to writes tests. In my current scenario, i have authentication library which verifies my "OTP" and after verifying it proceeds to do operation within the callback function.

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

I am unable to mock the callback to return null and carry on to test rest of the code. Following is my code snippet:

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作为"err",因此我可以测试其余代码.

I essentially want to call authy verify get a null as "err" in callback, so i can test the rest of the code.

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

Any help would be highly appreciated. Thanks

推荐答案

问题是您在测试和代码中使用了authy对象的不同实例.参见此处认证github存储库.

The trouble is that you're using different instances of the authy object in your tests and your code. See here authy github repo.

在您的代码中,您这样做

In your code you do

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

并在测试中

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

所以您的存根通常很好,但是它永远不会像这样工作,因为您的代码不使用您的存根.

So your stub is generally fine, but it will never work like this because your code does not use your stub.

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

A way out is to allow for the authy instance in your controller to be injected from the outside. Something like this:

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

这篇关于Sinon-如何存根身份验证库(Authy -Twilio)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆