Hi All,
in most of my files i have used below method -
var request = require('request');
request(url, function(error, response, body) {
if (!error && response.statusCode === 200) {
how do i stub this method in unit testing?
already tried sinon.stub(request), but thats not helping.
@simov tried already, but couldnt locate it, did anyone came across this issue already?
Try proxyquire:
var proxyquire = require('proxyquire');
var requestSpy = jasmine.createSpy();
var myFile = proxyquire('../../file/that/requires/request', {
request: requestSpy,
});
describe('the test', function() {
it('should use the mock', function() {
myFile.makeARequest();
expect(requestSpy).toHaveBeenCalledWith(jasmine.objectContaining({
headers: jasmine.objectContaining({
Accept: 'application/json',
}),
method: 'GET',
}), jasmine.any(Function));
});
});
Example: http://vansande.org/2015/03/22/unit_testing_with_mocks_in_node_js/
Or mock-require
var mock = require('mock-require');
var requestSpy = jasmine.createSpy();
mock('request', requestSpy);
var myFile = require('../../file/that/requires/request');
describe('the test', function() {
it('should use the mock', function() {
myFile.makeARequest();
expect(requestSpy).toHaveBeenCalled();
// and you should be able to invoke the callback also, e.g.
// var callback = requestSpy.calls.first().args[1];
// expect(callback(/* vars */))...
});
});
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Most helpful comment
Try proxyquire:
Example: http://vansande.org/2015/03/22/unit_testing_with_mocks_in_node_js/
Or mock-require