Reputation: 93
How do I use sinon.js to mock/spy object mentioned inside the javascript function? The mentioned object makes a method call as well and I need to test if the method is called by that object.
Any help will be appreciated.
Thanks a Million in advance!
Awaiting any response.
var ABCClient = require('ABCClient');
var connect = function(){
var client;
client = new ABCClient(); //instantiating object
client.on('some parameter'); // Test if the `on` event is called.
}
Upvotes: 3
Views: 4710
Reputation: 572
Looking at your mock. This is fairly straight forward once you step back and think about it. You are creating an instance of a class. Simply do this:
var ABCClient = require('ABCClient');
describe('test', function() {
it('some test', function() {
var stub = sinon.stub(ABCClient.prototype, 'on').yields('return object');
assert.ok(stub.calledWith('Parameter'));
ABCClient.prototype.on.restore();
});
});
Alternatively, you can just use spy
over stub
if you just want to spy on it without changing behaviour.
In this sample, you are stubbing the prototype
such that all the instances will have that property/method stubbed. Thus, you will be able to access the object. Give it a try and let me know.
Upvotes: 3