require-hijack
Version:
Hijack node require calls, with support for hijacking the entire module itself rather than only its properties. Handy for unit testing and mocking require calls in sub modules!
71 lines (49 loc) • 2.32 kB
Markdown
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](https://github.com/adamterlson/require-middleware) which redefines what `require` means.
## Basic usage
```````javascript
// 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 mocker
var requireHijack = require('require-hijack');
var fakeFs = sinon.stub(fs);
var replacement = requireHijack.replace('fs').with(fakeFs);
var myModule = require('../lib/myModule');
myModule.readDirectory();
fakeFs.readdir.should.have.been.called;
```````
*Note* - Hijack your sub-module's dependencies **before** loading your sub-module, otherwise those require calls will happen prior to the hijacking goodness!
### Paths
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`:
````````javascript
var requireHijack = require('require-hijack');
var fake = {};
// Paths passed work just like those to require, relative to the caller
requireHijack.replace('./fixtures/bar').with(fake);
// foo requires bar
require('./fixtures/foo');
``````````````````
In `/test/fixtures/foo.js`:
````````javascript
require('./bar') // Will yield the fake
``````````````````
## Restoring individual replacements
````````javascript
var newModule = {};
var replacement = requireHijack.replace('some-module').with(newModule);
//restore
replacement.restore();
require('some-module'); // Gets the real module
``````````````````
## Restoring all replacements
````````javascript
requireHijack.restoreAll();
``````````````````