Reputation: 1621
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();
});
Upvotes: 1
Views: 1415
Reputation: 1158
If you are stubbing the library, and not exporting from the original class file, you will need to import instead of referencing it as a method/property on the class
Then you'll want to use callsArg from sinon to call the callback
var ldapClient = ldap.createClient(ldapConfig);
...
var ldapStub;
before(()=>{
ldapStub = sinon
.stub(ldapClient, 'search')
.callsArg(2);
});
after(()=>{
ldapStub.restore();
});
You can then include assertions on the stub (for example ldapStub.calledOnce
should be true, etc)
Upvotes: 2