2016-11-11 36 views
0

我目前對Sinon,Mocha,Supertest以及編寫測試的過程都很陌生。在我目前的情況下,我有驗證庫驗證我的「OTP」,並驗證它繼續執行回調函數內的操作。Sinon - 如何驗證庫(Authy -Twilio)

我無法模擬回調返回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驗證得到一個空的回調「犯錯」,這樣我就可以測試代碼的其餘部分。

任何幫助將不勝感激。 謝謝

+0

@philnash,可以請你讓我怎麼嘲笑authy驗證 –

回答

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

感謝@nomve的答覆!一段時間以來,我一直在嘲笑我。你如何將一個參數傳遞給「控制器」。由於目前我正在調用一個「創建」功能,例如。 module.exports {create:function(req,res,next){..... –

+0

我不知道你的controller.js文件是怎麼樣的。然而,它看起來像,無論使用authy的代碼片段是什麼樣的,你都需要傳入你的stubbed實例。否則,你不能真正的存根。 – nomve