Nick Messing Nick Messing - 25 days ago 9
Node.js Question

How to mock dependencies for testing in node.js?

I want to write some unit-tests for my applicatin, can I somehow "mock" some dependencies used with require('dependencyname')?

Answer

You are looking for Proxyquire :)

//file1
var get    = require('simple-get');
var assert = require('assert');

module.exports = function fetch (callback) {
  get('https://api/users', callback);
};

//test file
var proxyquire = require('proxyquire');
var fakeResponse = {status:200};
var fetch = proxyquire('./get', {
  'simple-get': function (url, callback) {
    process.nextTick(function () {
      callback(null, fakeResponse)
    })
  }
});

fetch(function (err, res) {
  assert(res.statusCode, 200)
});

Straight out of their docs.

Comments