Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unit test cases for request(url, function(error, response, body) method #2181

Closed
svlungade opened this issue Apr 18, 2016 · 3 comments
Closed

Comments

@svlungade
Copy link

svlungade commented Apr 18, 2016

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.

@svlungade
Copy link
Author

@simov tried already, but couldnt locate it, did anyone came across this issue already?

@tstapleton
Copy link

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 */))...
    });
});

@stale
Copy link

stale bot commented Nov 23, 2018

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.

@stale stale bot added the stale label Nov 23, 2018
@stale stale bot closed this as completed Nov 30, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants