• Stars
    star
    3,078
  • Rank 14,624 (Top 0.3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easy monkey-patching for node.js unit tests

rewire

Easy monkey-patching for node.js unit tests

Dependency Status Build Status Coverage Status

rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may

  • inject mocks for other modules or globals like process
  • inspect private variables
  • override variables within the module.

Please note: The current version of rewire is only compatible with CommonJS modules. See Limitations.


Installation

npm install rewire


Introduction

Imagine you want to test this module:

// lib/myModule.js
// With rewire you can change all these variables
var fs = require("fs"),
    path = "/somewhere/on/the/disk";

function readSomethingFromFileSystem(cb) {
    console.log("Reading from file system ...");
    fs.readFile(path, "utf8", cb);
}

exports.readSomethingFromFileSystem = readSomethingFromFileSystem;

Now within your test module:

// test/myModule.test.js
var rewire = require("rewire");

var myModule = rewire("../lib/myModule.js");

rewire acts exactly like require. With just one difference: Your module will now export a special setter and getter for private variables.

myModule.__set__("path", "/dev/null");
myModule.__get__("path"); // = '/dev/null'

This allows you to mock everything in the top-level scope of the module, like the fs module for example. Just pass the variable name as first parameter and your mock as second.

var fsMock = {
    readFile: function (path, encoding, cb) {
        expect(path).to.equal("/somewhere/on/the/disk");
        cb(null, "Success!");
    }
};
myModule.__set__("fs", fsMock);

myModule.readSomethingFromFileSystem(function (err, data) {
    console.log(data); // = Success!
});

You can also set multiple variables with one call.

myModule.__set__({
    fs: fsMock,
    path: "/dev/null"
});

You may also override globals. These changes are only within the module, so you don't have to be concerned that other modules are influenced by your mock.

myModule.__set__({
    console: {
        log: function () { /* be quiet */ }
    },
    process: {
        argv: ["testArg1", "testArg2"]
    }
});

__set__ returns a function which reverts the changes introduced by this particular __set__ call

var revert = myModule.__set__("port", 3000);

// port is now 3000
revert();
// port is now the previous value

For your convenience you can also use the __with__ method which reverts the given changes after it finished.

myModule.__with__({
    port: 3000
})(function () {
    // within this function port is 3000
});
// now port is the previous value again

The __with__ method is also aware of promises. If a thenable is returned all changes stay until the promise has either been resolved or rejected.

myModule.__with__({
    port: 3000
})(function () {
    return new Promise(...);
}).then(function () {
    // now port is the previous value again
});
// port is still 3000 here because the promise hasn't been resolved yet

Limitations

Babel's ES module emulation
During the transpilation step from ESM to CJS modules, Babel renames internal variables. Rewire will not work in these cases (see #62). Other Babel transforms, however, should be fine. Another solution might be switching to babel-plugin-rewire.

Variables inside functions
Variables inside functions can not be changed by rewire. This is constrained by the language.

// myModule.js
(function () {
    // Can't be changed by rewire
    var someVariable;
})()

Modules that export primitives
rewire is not able to attach the __set__- and __get__-method if your module is just exporting a primitive. Rewiring does not work in this case.

// Will throw an error if it's loaded with rewire()
module.exports = 2;

Globals with invalid variable names
rewire imports global variables into the local scope by prepending a list of var declarations:

var someGlobalVar = global.someGlobalVar;

If someGlobalVar is not a valid variable name, rewire just ignores it. In this case you're not able to override the global variable locally.

Special globals
Please be aware that you can't rewire eval() or the global object itself.


API

rewire(filename: String): rewiredModule

Returns a rewired version of the module found at filename. Use rewire() exactly like require().

rewiredModule.__set__(name: String, value: *): Function

Sets the internal variable name to the given value. Returns a function which can be called to revert the change.

rewiredModule.__set__(obj: Object): Function

Takes all enumerable keys of obj as variable names and sets the values respectively. Returns a function which can be called to revert the change.

rewiredModule.__get__(name: String): *

Returns the private variable with the given name.

rewiredModule.__with__(obj: Object): Function<callback: Function>

Returns a function which - when being called - sets obj, executes the given callback and reverts obj. If callback returns a promise, obj is only reverted after the promise has been resolved or rejected. For your convenience the returned function passes the received promise through.


Caveats

Difference to require()
Every call of rewire() executes the module again and returns a fresh instance.

rewire("./myModule.js") === rewire("./myModule.js"); // = false

This can especially be a problem if the module is not idempotent like mongoose models.

Globals are imported into the module's scope at the time of rewiring
Since rewire imports all gobals into the module's scope at the time of rewiring, property changes on the global object after that are not recognized anymore. This is a problem when using sinon's fake timers after you've called rewire().

Dot notation
Although it is possible to use dot notation when calling __set__, it is strongly discouraged in most cases. For instance, writing myModule.__set__("console.log", fn) is effectively the same as just writing console.log = fn. It would be better to write:

myModule.__set__("console", {
    log: function () {}
});

This replaces console just inside myModule. That is, because rewire is using eval() to turn the key expression into an assignment. Hence, calling myModule.__set__("console.log", fn) modifies the log function on the global console object.


webpack

See rewire-webpack


CoffeeScript

Good news to all caffeine-addicts: rewire works also with Coffee-Script. Note that in this case you need to install the coffeescript package.


License

MIT

More Repositories

1

rewire-webpack

Dependency injection for webpack bundles
JavaScript
121
star
2

bumpy-road-to-universal-javascript

Example repository for my talk "The bumpy road to Universal JavaScript"
JavaScript
33
star
3

spa-vs-universal

Real-world example implementation of a blog using a SPA and a universal architecture. Demonstrates server-side rendering combined with code-splitting.
JavaScript
31
star
4

toSrc

Turns every JavaScript object or primitive into valid source code that can be evaled again.
JavaScript
19
star
5

webpack-config-tips

Not so secret tips and examples on how to write good webpack configs.
HTML
19
star
6

popular-javascript-projects

Scripts that I have used to retrieve and process data about JavaScript projects from Github, npm, StackOverflow etc.
JavaScript
16
star
7

JSONPoo

Like JSONP, but better
9
star
8

webpack-browser-benchmark

An I/O independent webpack build for browser benchmarks
JavaScript
4
star
9

webpack-extract-index-html

Example project that demonstrates how the ExtractTextWebpackPlugin can be used to generate an index.html
JavaScript
4
star
10

slides-frontend-optimization

HTML
2
star
11

browserify-bypass

A node.js browserify middleware to declare alternative requires for the browser
2
star
12

hello-rust

Rust example project that can be published on NPM as WebAssembly module
Rust
2
star
13

webpack-hash-test

This repository can be used to check if and under what circumstances webpack may produce different hashes. See https://github.com/webpack/webpack/issues/1479
JavaScript
2
star
14

webpack-broken-source-maps

This repository demonstrates a common problem where webpack loaders are responsible for broken source maps.
JavaScript
2
star
15

woerdl

JavaScript
1
star
16

visual-bank-account

Visualizes earnings and spendings of your bank account
JavaScript
1
star
17

nuxt-pwa-build-perf-demo

A repository to demonstrate a problem with the Nuxt PWA plugin that slows down the build
Vue
1
star
18

haskell-experiments

Haskell experiments
Haskell
1
star
19

worker-message-performance

Performance test of message passing between the main thread and a service- or web-worker.
HTML
1
star
20

premailer

Simple API-wrapper for http://premailer.dialect.ca to sanitize HTML-mails
1
star
21

prisma-bug-repo

A repository for reproducing Prisma bugs
1
star
22

ts-node-tests

1
star