Skip to content

Stubbing non object imports

kirbysayshi edited this page Dec 10, 2014 · 2 revisions

Modules that export a primitive are tricky to stub (they are also rare, but useful for things like localized strings). Here are a few techniques.

String / Numbers

foo.js:

module.exports = "the real thing"

stub:

var proxyquire = require('proxyquire');
var foo = proxyquire('foo', {
  foo: new String('a fake thing')
});

If you need to use one of proxyquire's directives, like @global, a IIFE works:

var proxyquire = require('proxyquire');
var foo = proxyquire('foo', {
  foo: (function() {
    var s = new String('a fake thing')
    s['@global'] = true;
    return s;
  }())
});

CAVEATS

Because you are now using a String Object instead of primitive string, a type-checked comparison will fail:

> var a = 'what';
undefined
> var b = new String('what')
undefined
> a === b
false

A more common case might be:

var str = new String('');
if (str) { console.log('GOTCHA') }

The same goes for numbers.

Clone this wiki locally