Skip to content

Instantly share code, notes, and snippets.

@kimus
Last active February 23, 2022 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kimus/9434a670ca84c6814633061e46825f0a to your computer and use it in GitHub Desktop.
Save kimus/9434a670ca84c6814633061e46825f0a to your computer and use it in GitHub Desktop.
Inject mock data or an module into Node require
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');
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