node.js – 使用mockery和sinon模拟一个类方法

前端之家收集整理的这篇文章主要介绍了node.js – 使用mockery和sinon模拟一个类方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在学习使用sinon的节点模块mockery进行单元测试.

仅使用mockery和普通类我能够成功注入模拟.但是我想注入一个sinon存根而不是一个简单的类,但是我遇到了很多麻烦.

我试图嘲笑的课程:

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

这是我目前在我的beforeEach()函数中使用的代码

  1. beforeEach(function() {
  2. ldapAuthMock = sinon.stub(LdapAuth.prototype,"authenticate",function(username,callback) {});
  3. mockery.registerMock('ldapauth-fork',ldapAuthMock);
  4. mockery.enable();
  5. });
  6.  
  7. afterEach(function () {
  8. ldapAuthMock.restore();
  9. mockery.disable();
  10. });

我试图以各种方式模拟/存根LdapAuth类但没有成功,上面的代码只是最新版本无效.

所以我只想知道如何使用sinon和mockery成功地模拟这个.

解决方法

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

幸运的是,Sinon还负责修改你试图模拟的对象,并提供一个很好的API来构建spys,subs和mocks.

这是一个关于如何存根authenticate方法的小例子:

  1. // ldap-auth.js
  2.  
  3. function LdapAuth(options) {
  4. }
  5.  
  6. LdapAuth.prototype.authenticate = function (username,callback) {
  7. callback(null,'original');
  8. }
  9.  
  10. module.exports = LdapAuth;
  1. // test.js
  2.  
  3. var sinon = require('sinon');
  4. var assert = require('assert');
  5. var LdapAuth = require('./ldap-auth');
  6.  
  7. describe('LdapAuth#authenticate(..)',function () {
  8. beforeEach(function() {
  9. this.authenticateStub = sinon
  10. // Replace the authenticate function
  11. .stub(LdapAuth.prototype,'authenticate')
  12. // Make it invoke the callback with (null,'stub')
  13. .yields(null,'stub');
  14. });
  15.  
  16. it('should invoke the stubbed function',function (done) {
  17. var ldap = new LdapAuth();
  18. ldap.authenticate('user','pass',function (error,value) {
  19. assert.ifError(error);
  20. // Make sure the "returned" value is from our stub function
  21. assert.equal(value,'stub');
  22. // Call done because we are testing an asynchronous function
  23. done();
  24. });
  25. // You can also use some of Sinon's functions to verify that the stub was in fact invoked
  26. assert(this.authenticateStub.calledWith('user','pass'));
  27. });
  28.  
  29. afterEach(function () {
  30. this.authenticateStub.restore();
  31. });
  32. });

我希望这有帮助.

猜你在找的Node.js相关文章