2015-02-09 22 views
6

我正在学习使用sinon的节点模块嘲笑进行单元测试。模拟使用嘲讽和sinon的类方法

仅使用嘲讽和普通类我能够成功注入模拟。不过我想注入一个sinon stub而不是一个普通的类,但是我遇到了很多麻烦。

类我试图嘲弄:

function LdapAuth(options) {} 

// The function that I want to mock. 
LdapAuth.prototype.authenticate = function (username, password, callback) {} 

这里是我目前使用在我beforeEach()函数的代码:我试图嘲弄

beforeEach(function() { 
     ldapAuthMock = sinon.stub(LdapAuth.prototype, "authenticate", function(username, password, callback) {}); 
     mockery.registerMock('ldapauth-fork', ldapAuthMock); 
     mockery.enable(); 
    }); 

    afterEach(function() { 
     ldapAuthMock.restore(); 
     mockery.disable(); 
    }); 

/以各种方式对LdapAuth类进行存根没有成功,上面的代码只是最新的版本,不起作用。

所以我只是想知道如何使用sinon和嘲笑成功地嘲笑这一点。

回答

9

由于Node的模块缓存,Javascript的动态特性以及它的原型继承,这些节点模拟库可能非常麻烦。

幸好Sinon还负责修改您尝试模拟的对象,并提供一个很好的API来构建spys,subs和mocks。

这里是我将如何存根authenticate方法的一个小例子:

// ldap-auth.js 

function LdapAuth(options) { 
} 

LdapAuth.prototype.authenticate = function (username, password, callback) { 
    callback(null, 'original'); 
} 

module.exports = LdapAuth; 
// test.js 

var sinon = require('sinon'); 
var assert = require('assert'); 
var LdapAuth = require('./ldap-auth'); 

describe('LdapAuth#authenticate(..)', function() { 
    beforeEach(function() { 
    this.authenticateStub = sinon 
           // Replace the authenticate function 
           .stub(LdapAuth.prototype, 'authenticate') 
           // Make it invoke the callback with (null, 'stub') 
           .yields(null, 'stub'); 
    }); 

    it('should invoke the stubbed function', function (done) { 
    var ldap = new LdapAuth(); 
    ldap.authenticate('user', 'pass', function (error, value) { 
     assert.ifError(error); 
     // Make sure the "returned" value is from our stub function 
     assert.equal(value, 'stub'); 
     // Call done because we are testing an asynchronous function 
     done(); 
    }); 
    // You can also use some of Sinon's functions to verify that the stub was in fact invoked 
    assert(this.authenticateStub.calledWith('user', 'pass')); 
    }); 

    afterEach(function() { 
    this.authenticateStub.restore(); 
    }); 
}); 

我希望这有助于。

+1

如果你想存根构造函数呢? – 2017-03-01 17:49:26