Mock a class method using mockery and sinon

☆樱花仙子☆ 提交于 2019-12-05 08:12:16

These node mocking libraries can be quite cumbersome because of Node's module cache, Javascript's dynamic nature and it's prototypical inheritance.

Fortunately Sinon also takes care of modifying the object you are trying to mock as well as providing a nice API to construct spys, subs and mocks.

Here is a small example of how I would stub the authenticate method:

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

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!