Comment

Comment by daniellmb

Using the NODE_ENV is nice simple solution but when you need more there is a great dependency injection module called rewire that adds a special setter and getter to modules so you can modify their behavior such as: inject mocks for other modules or globals like process, leak private variables override variables within the module.

This is especially nice because you don't need to add any special if statements to the module code you just load your module under test using rewire instead of require.

// file: test-stats-rewire.js

var rewire = require('rewire');

var assert = require('assert');

var stats = rewire('./stats');

// leak private method sum for testing

var sum = stats.__get__('sum');

assert.equal(sum([1]), 1);

assert.equal(sum([1, 2, 3]), 6);

parent daniellmb 12 years ago

No comments yet

Be the first to share your thoughts.

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton