Skip to content

Instantly share code, notes, and snippets.

@MandarinConLaBarba
Last active December 31, 2021 22:24
Show Gist options
  • Select an option

  • Save MandarinConLaBarba/4533303 to your computer and use it in GitHub Desktop.

Select an option

Save MandarinConLaBarba/4533303 to your computer and use it in GitHub Desktop.
How to spy on node's require() w/ sinon.js
//If you need to spy or stub the global require function in node.js, don't try to spy on the require function itself..you aren't going //to be successful.
//Instead, spy on the require.extensions object like so:
var spies = {};
spies.require = sinon.spy(require.extensions, '.js');
//Then when you need to assert you can do stuff like:
spies.require.firstCall.args[1].should.include("path/to/some/module");
//Don't forget to clear cached modules if you want to make sure they are called...
//I'm sure there are other ways to do this, but if you want a module or set of modules cleared during tear-down, you can try
//something like this:
_.each(require.cache, function(cachedModule, indx) {
if (indx.indexOf("path/to/some/module") >= 0) {
delete require.cache[indx];
}
});
@micalevisk
Copy link
Copy Markdown

micalevisk commented Dec 31, 2021

require.extensions is deprecated now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment