Proxyquire

Test cases always involves mocks and stub, sometimes there will be a need to mock require itself, that where proxyquire comes for our rescue.

Proxyquire: Proxies nodejs require in order to allow overriding dependencies during testing.

Installing proxyquire: npm install -D proxyquire

Example:

Say we a file baz.js under test and it looks like:

12345

varos=require('os');module.exports=function(){returnos.freemem();}

It's evident that the return value of this function will never be a constant value.

How do we test it then?

Have a look at the test case:

1234567891011121314151617

// Get some assertion helper.varassert=require('assert');// First up we require proxyquirevarproxyquire=require('proxyquire');// We make a mock of what we need.varosStub={freemem:function(){return617619456;}}// Now some magic ;)varfreemem=proxyquire("./baz",{'os':osStub});it("should return the amount of free memory",function(){assert.equal(freemem(),6176197456);});