Monday, 12 August 2019

How to mock events with sinon?

Here is my simple program where I'm trying to get user's data via ldapClient. I need to test it without internet connection so wondering how to mock that result.on events to return appropriate data.

var request = require('request');
var ldap = require('ldapjs');

....
var ldapClient = ldap.createClient(ldapConfig);
....


var MY_CLASS = {
    getData: function (userId, cb) {
        if (!ldapConfig) {
            return cb(new Error('ldap is not configured'));
        }

        ldapClient.search('xxxx.com', { ldapConfig },
            function (err, result) {
                if (err) {
                    return cb(err);
                }

                result.on('searchEntry', function (entry) {
                    if (entry) {
                        return entry;
                    }
                });

                result.on('error', function (err) {
                    cb(err);
                });

                result.on('end', function () {
                    cb(null, 'END');
                });
            });
    }
};

module.exports = MY_CLASS;

Looking for something (see below) but assume I need to use a spy. But how do I define it in that deep nested class?

before(()=>{
    sinon
    .stub(MY_CLASS.ldapClient, 'search')
    .yields(???);
});
after(()=>{
    MY_CLASS.ldapClient.search.restore();
});



from How to mock events with sinon?

No comments:

Post a Comment