Last active
December 13, 2015 16:39
-
-
Save shesek/4942247 to your computer and use it in GitHub Desktop.
Require a file, and mock the modules returned to it from require()
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
Module = require 'module' | |
# native_module isn't public, mock the needed functionality | |
NativeModule = do (natives = Object.keys process.binding 'natives') -> | |
exists: (name) -> name in natives | |
require: require | |
mock = (request, parent, modules) -> | |
return modules[request] if request of modules | |
return NativeModule.require request if NativeModule.exists request | |
path = Module._resolveFilename request, parent | |
return modules[path] if path of modules | |
module = new Module path, parent | |
module.require = (filename) -> mock filename, module, modules | |
modules[path] = module.exports | |
# see https://github.com/joyent/node/commit/bf9d8e9214e2098bacf18416564dc3a91bcdf5d6 | |
# w.r.t try..finally usage | |
hadException = true | |
try | |
module.load path | |
hadException = false | |
modules[path] = module.exports | |
finally | |
delete modules[path] if hadException | |
module.exports = mock | |
# Licensed under WTFPL |
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
mock_require = require 'mock-require' | |
mock_require 'some_file', module, fs: mocked_fs_module, http: mocked_http_module | |
# note that `module` is passed as the `parent` argument, so that require() paths are resolved | |
# relative to the current file path. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment