45

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?

Armand
  • 23,463
  • 20
  • 90
  • 119

1 Answers1

95

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

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
  • 5
    Wonderful man, thank you. From the docs: `They support the full test spy API in addition to methods which can be used to alter the stub’s behavior.` – Armand May 27 '15 at 15:58