Wash class method using mockery and sine

I am participating in a unit test using modular node modulation with synon.

Using only bullying and a simple class, I can successfully implement the layout. However, I would like to add a sine stub instead of a simple class, but I have a lot of problems with this.

The class I'm trying to make fun of:

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

And here is the code that I use in my beforeEach () function:

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

I tried to make the mdock / stub class LdapAuth in various ways without success, and the code above is just the latest version that doesn't work.

So, I just want to know how to mock it using sine and mockery.

+6
source share
1 answer

These node ridiculous libraries can be rather cumbersome due to the node module cache, the dynamic nature of Javascript and its prototypal inheritance.

Fortunately, Sinon also takes care of modifying the object you are trying to make fun of, as well as providing a good API for creating spys, subs and mocks.

Here is a small example of how I close 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 functions to verify that the stub was in fact invoked assert(this.authenticateStub.calledWith('user', 'pass')); }); afterEach(function () { this.authenticateStub.restore(); }); }); 

Hope this helps.

+9
source

Source: https://habr.com/ru/post/982211/


All Articles