Last active
December 31, 2021 22:24
-
-
Save MandarinConLaBarba/4533303 to your computer and use it in GitHub Desktop.
How to spy on node's require() w/ sinon.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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]; | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
require.extensions
is deprecated now