In the following example, I want to stub the get
function to prevent the actual HTTP request from occurring. I want to spy on the get
method to check what arguments it was called with.
var request = require('request'), sinon = require('sinon'); describe('my-lib', function() { sinon.stub(request, 'get').yield(null, null, "{}"); var spy = sinon.spy(request, 'get'); it('should GET some data', function(done) { function_under_test(function(err, response) { if(error) return done(error); assert(request.get.called); assert(request.get.calledWith('some', 'expected', 'args')); }); }); });
Sinon does not seem to allow spying and stubbing the same method, though. The above example gives the following error:
TypeError: Attempted to wrap get which is already wrapped
How do I spy on a method, while preventing default behaviour?
Spies are almost the opposite of stubs. They allow the doubled entity to retain its original behavior while providing information about how it interacted with the code under test. The spy can tell the test what parameters it was given, how many times it was called, and what, if any, the return value was.
The sinon. stub() substitutes the real function and returns a stub object that you can configure using methods like callsFake() . Stubs also have a callCount property that tells you how many times the stub was called. For example, the below code stubs out axios.
When using mock objects, the default behavior of methods (when not stubbed) is do nothing (performs nothing.) When using spy objects, the default behavior of the methods (when not stubbed) is the real method behavior. In our previous tutorials, we have discussed some examples of stubbing, mocking, and spying.
The function sinon. spy returns a Spy object, which can be called like a function, but also contains properties with information on any calls made to it. In the example above, the firstCall property has information about the first call, such as firstCall. args which is the list of arguments passed.
The stub supports all the methods of a spy. Just don't create the spy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With