简体   繁体   中英

Spy on require in Node.js

Inside a unit-test I want to verify whether the SUT calls require with a specific parameter. Basically my SUT is a small module with the following implementation:

module.exports = function () {
  require('foo');
};

I now want to write a test like this:

var sut = require('./sut');
it('requires foo.', function () {
  sut();
  expect( ??? );
});

So the question is: How do I verify whether require was called with the correct parameters? I tried it using a Sinon.js spy:

var spy = sinon.spy(require);
sut();
expect(spy.callCount).to.be.equal(1);
expect(spy.calledWithExactly('foo')).to.be(true);
require.restore();

But this doesn't work. When I run my test, Mocha tells me:

Error: expected 0 to equal 1

What am I doing wrong, and how can I fix it?

PS: I do not need to work with Sinon.js, so if another module is better suited for my case, everything else is fine as well.

There is a module called proxyquire with which you can override dependencies for unit testing purpopses: https://npmjs.org/package/proxyquire

Your unit test may then look like this:

var proxyquire =  require('proxyquire');

var sut = proxyquire('./sut', { 'foo': function(){ /* insert test code here */ });

I'm not sure if that is exactly what you want, but maybe you'll find it helpful.

You could try rewire . It gives you private access to modules for testing purposes. Then you could inspect the module.children -variable to check for the dependency.

Given you want to check if module a.js requires b.js it would look like:

var rewire = require("rewire");
var a = rewire("./a.js"); // using rewire instead of require

var pathToB = require.resolve("./b.js");
var aModule = a.__get__("module"); // leaking the private module-variable

assert.ok(aModule.children.some(function (module) {
    return module.filename === pathToB;
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM