To handle globs in jest, I created a custom preprocessor to manually process the files. By controlling the processing of files and initializing the processor myself, I was able to effectively handle globs.
// config.js
module.exports = {
transform: {
'.': `./path/to/your/processor.js`
// processor.js
const path = require(`path`);
const glob = require(`glob`).sync;
const yourProcessor = // require your processor code - ts-jest, babel-jest, esbuild-jest, etc
module.exports = {
process(src, filename, config, opts) {
const dir = path.dirname(filename);
src = processGlob(src, dir);
return yourProcessor(src, filename, config, opts);
},
};
function processGlob(src, dir) {
// This function handles matching imports with globs
return src.replace(/^import\s'(.*\*.*)';$/m, (_match, pathCapture) => {
const matcher = /.+\..+/;
const files = glob(pathCapture, {cwd: dir})
.sort()
.filter((path) => matcher.test(path));
return `${files.map((module, index) => `import * as module${index} from '${module}'`).join(`;`)}`;
});
}
It's worth noting that this approach allows for one glob import per file using the map indexes for each module name. If you need multiple glob imports in one file, consider tracking a global count variable instead.