Use SinonJS to stub and spy on the same function?

Armand picture Armand · May 27, 2015 · Viewed 8.6k times · Source

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?

Answer

Robert Moskal picture Robert Moskal · May 27, 2015

The stub supports all the methods of a spy. Just don't create the spy.