Mock node require calls, with support for mocking the entire module itself rather than only its properties
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.

Require Hijack

This library enables mocking require calls. This is particularly useful when unit testing a module that depends on another sub-module.

How it differs:

  • It allows for mocking of the ENTIRE module (meaning a Class's constructor can be replaced, or if the module is nothing more than a function the entire function can be replaced).
  • It works without touching the require cache, so it will work on native modules as well (such as fs).
  • Doesn't spawn a vm.
  • This module itself doesn't touch the inside of require, though it leverages require-middleware which redefines what require means.

Basic usage

// This call to the real dependency is only required to quickly stub out the entire thing.
// You can pass any sort of object or function to `with()`
var realfs = require('fs');

// From this point on out, all require calls will go through the hijacker
// Any calls not hijacked will be totally unaffected
var requireHijack = require('require-hijack');

var fakeFs = sinon.stub(realfs);
var replacement = requireHijack.replace('fs').with(fakeFs);

var myModule = require('../lib/myModule');


Note - Hijack your sub-module's dependencies before loading your sub-module, otherwise those require calls will happen prior to the hijacking goodness!


Paths used are relative to the module doing the hijacking and not the module doing the requiring, in this way it can be referenced just like require and totally unambiguously.

In /test/test.js:

var requireHijack = require('require-hijack');
var fake = {};
// Paths passed work just like those to require, relative to the caller

// foo requires bar

In /test/fixtures/foo.js:

require('./bar') // Will yield the fake

Restoring individual replacements

var newModule = {};
var replacement = requireHijack.replace('some-module').with(newModule);


require('some-module'); // Gets the real module

Restoring all replacements