Nick Messing Nick Messing - 1 year ago 75
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 Source

You are looking for Proxyquire :)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download