Last active
February 23, 2022 23:50
-
-
Save kimus/9434a670ca84c6814633061e46825f0a to your computer and use it in GitHub Desktop.
Inject mock data or an module into Node 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
require('./require-inject') | |
.inject('@mock/direct.json', { bla: 1 }) | |
.inject('@mock/file.json', require('./mock/file.json')) | |
.inject('module-name', require('./some/module')); | |
const data1 = require('@mock/direct.json'); | |
const data2 = require('@mock/file.json'); | |
const mod1 = require('module-name'); |
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 path = require('path'); | |
const m = require('module'); | |
const root = path.join(path.resolve('.'), 'node_modules'); | |
function get(res) { | |
const id = resolve(res); | |
const mod = require.cache[id]; | |
return { | |
id: id, | |
exists: mod !== undefined, | |
mock: mod ? mod.mock : false | |
}; | |
} | |
// store real resolve function and add a fake resolver | |
const real_resolveFilename = m._resolveFilename; | |
m._resolveFilename = (request, parent) => { | |
// check if it's a 'fake' and return the id | |
// this is for getting non-existent files | |
const mod = get(request); | |
if (mod.mock) { | |
return mod.id; | |
} | |
// if it's not a 'fake' one, just use the defaut resolver | |
return real_resolveFilename(request, parent); | |
}; | |
// this could be better, but for normal usage it's enougth | |
function resolve(file) { | |
// check if it's a module name (not absolute or relative) | |
if (!path.isAbsolute(file) && /^[a-z]+/i.test(file)) { | |
// return a 'fake' path using the default node_modules root | |
return path.join(root, file, 'index.js'); | |
} | |
return path.resolve(file); | |
} | |
const Injector = { | |
inject: (name, exp) => { | |
// check if the module already registered or not | |
const mod = get(name); | |
if (!mod.exists) { | |
const res = mod.id; | |
require.cache[res] = { | |
id: res, | |
filename: res, | |
loaded: true, | |
mock: true, | |
exports: exp | |
}; | |
} | |
// return the injector for composable injects | |
return Injector; | |
}, | |
// yes we could add a method for removing the injectables | |
// but, that's easy and this is just an example on it could be done | |
} | |
module.exports = Injector; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment