Testing Node.js with Mocha, Expect.js, and Nock

Problem: Your Node.js code uses request or http to make http requests to URLs. You don’t want to make actual http calls, nor do you want to test request and/or http. How can you test that your code works as intended and interfaces properly with request and http?

Solution: Use nock. For the purposes of this example, I’ll also demonstrate how nock works in concert with mocha and expect.js.

Your node module

// Let's call this file/module flickr-feeder.js
var request = require("request")
  , _ = require("underscore");

exports.getFlickrJSON = function(params, callback) {
  var url = "http://api.flickr.com/services/feeds/photos_public.gne";
  var paramsObj = {
    'format': 'json'
  };

  _.extend(paramsObj, params);

  request(url, {qs: paramsObj}, function (error, response, body) {
    callback(body);
  });
};

Example Usage

var ff = require('flickr-feeder');
// get JSON data from http://api.flickr.com/services/feeds/photos_public.gne?id=someFlickrID&format=json
ff.getFlickrJSON({id: 'someFlickrID'}, function (data) {
  console.log(data); // the JSON response from Flickr
});

Test Code

// This file is lives in test/flickr-feeder.js
var flickrFeeder = require('../flickr-feeder.js')
  , nock = require('nock')
  , expect = require('expect.js');

describe("flickrFeeder", function() {
  describe("#getFlickrJSON", function () {

    // verify that the getFlickrJSON method exists
    it("exists as a public method on flickrFeeder", function () {
      expect(typeof flickrFeeder.getFlickrJSON).to.eql('function');
    });

    // verify that the getFlickrJSON method calls the correct URL
    it("makes the correct http call to Flickr's API based on the parameters it's passed", function () {

      // use nock
      nock('http://api.flickr.com')
        .get('/services/feeds/photos_public.gne?format=json&id=someFlickrID')
        .reply(200, {'some_key':'some_value'});

      flickrFeeder.getFlickrJSON({id: 'someFlickrID'}, function (data) {
        expect(data).to.eql({'some_key':'some_value'});
      });
    });
  });
});

Run your test

cd your_flickr_feeder_directory
mocha

See the full example code on Github here.