Skip to content

Instantly share code, notes, and snippets.

@ajsaraujo
Created March 15, 2022 11:54
Show Gist options
  • Save ajsaraujo/c1ff492be98f8f7fa01372ca4b2bb18b to your computer and use it in GitHub Desktop.
Save ajsaraujo/c1ff492be98f8f7fa01372ca4b2bb18b to your computer and use it in GitHub Desktop.
Fix jest config Nx v13
const path = require('path');
const fs = require('fs');
const { promisify, inspect } = require('util');
async function getAllJestConfigJsFilePaths(directory) {
const readDir = promisify(fs.readdir);
const stat = promisify(fs.stat);
const files = await readDir(directory);
const jestConfig = 'jest.config.js';
if (files.includes(jestConfig)) {
return path.join(directory, jestConfig);
}
const childFilesPromise = files
.map((fileName) => path.join(directory, fileName))
.map(async (path) => {
const stats = await stat(path);
return { stats, path };
});
const childFiles = await Promise.all(childFilesPromise);
const childDirectories = childFiles.filter((file) =>
file.stats.isDirectory()
);
return Promise.all(
childDirectories.map((dir) => dir.path).map(getAllJestConfigJsFilePaths)
);
}
function fixConfig(configObject) {
const updates = {
moduleFileExtensions: ['ts', 'html', 'js', 'json', 'mjs'],
extensionsToTreatAsEsm: ['.ts'],
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
transform: {
'^.+\\.(ts|js|mjs|html|svg)$': 'jest-preset-angular',
},
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
],
transformIgnorePatterns: [
`node_modules/(?!@angular|@ngneat/spectator|array-move|lodash-es)`,
],
};
Object.assign(configObject, updates);
configObject.globals['ts-jest'] = {
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
};
return configObject;
}
function writeBack(file) {
const write = promisify(fs.writeFile);
return write(file.path, stringify(file.config));
}
function stringify(object) {
return `module.exports = ${inspect(object)}`;
}
(async function f() {
// You will probably have to change this
const appsFolder = path.join(__dirname, '..', '..', '..', 'apps');
const libsFolder = path.join(__dirname, '..', '..', '..', 'libs');
const jestConfigFilePaths = await Promise.all([
...(await getAllJestConfigJsFilePaths(appsFolder)),
...(await getAllJestConfigJsFilePaths(libsFolder)),
]);
await Promise.all(
jestConfigFilePaths
.flat(5)
.map((path) => ({ path, config: fixConfig(require(path)) }))
.map((file) => writeBack(file))
);
})();
@ajsaraujo
Copy link
Author

Fixes all jest.config.js in a Nx workspace so they work with Nx v13. Based on this StackOverflow thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment