我正在学习使用sinon的节点模块mockery进行单元测试.
仅使用mockery和普通类我能够成功注入模拟.但是我想注入一个sinon存根而不是一个简单的类,但是我遇到了很多麻烦.
我试图嘲笑的课程:
function LdapAuth(options) {} // The function that I want to mock. LdapAuth.prototype.authenticate = function (username,password,callback) {}
beforeEach(function() { ldapAuthMock = sinon.stub(LdapAuth.prototype,"authenticate",function(username,callback) {}); mockery.registerMock('ldapauth-fork',ldapAuthMock); mockery.enable(); }); afterEach(function () { ldapAuthMock.restore(); mockery.disable(); });
我试图以各种方式模拟/存根LdapAuth类但没有成功,上面的代码只是最新版本无效.
所以我只想知道如何使用sinon和mockery成功地模拟这个.
解决方法
由于Node的模块缓存,Javascript的动态特性以及它的原型继承,这些节点模拟库可能非常麻烦.
幸运的是,Sinon还负责修改你试图模拟的对象,并提供一个很好的API来构建spys,subs和mocks.
这是一个关于如何存根authenticate方法的小例子:
// ldap-auth.js function LdapAuth(options) { } LdapAuth.prototype.authenticate = function (username,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(); }); });
我希望这有帮助.