Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use sinon.js to mock/spy object mentioned inside the javascript function?

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.
}
like image 236
Harsh Avatar asked Sep 04 '26 06:09

Harsh


1 Answers

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.

like image 193
lwang135 Avatar answered Sep 06 '26 21:09

lwang135



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!