-
-
Save nlf/52ca6adab49e5b3939ba37c7f0fc51c6 to your computer and use it in GitHub Desktop.
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
const Module = require('module') | |
const applyMocks = function (id, mocks) { | |
const filePath = Module._resolveFilename(id, module.parent) | |
if (!Module._cache[filePath]) { | |
Module._load(id, module.parent, false) | |
} | |
const mod = Module._cache[filePath] | |
const originalExports = mod.exports | |
const originalRequire = mod.require | |
mod.require = function (id) { | |
if (id in mocks) { | |
return mocks[id] | |
} | |
return originalRequire.call(this, id) | |
} | |
mod.loaded = false | |
mod.load(mod.filename) | |
const mocked = mod.exports | |
mod.require = originalRequire | |
mod.exports = originalExports | |
return mocked | |
} | |
module.exports = applyMocks |
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
const q = require('./q') | |
module.exports = function () { | |
return q() | |
} |
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.exports = function () { return 'original' } |
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
const applyMocks = require('./mock') | |
const p = require('./p') | |
console.log(p()) // logs 'original' | |
const mocked = applyMocks('./p', { | |
'./q': function () { return 'overwritten' } | |
}) | |
console.log(mocked()) // logs 'overwritten' | |
const p2 = require('./p') | |
console.log(p2()) // logs 'original' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment