Skip to content

Commit

Permalink
fix: make jest ESM-ready
Browse files Browse the repository at this point in the history
  • Loading branch information
mizdra committed Dec 19, 2021
1 parent 9ec15c9 commit 0e5caf8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
8 changes: 6 additions & 2 deletions jest.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,21 @@
// eslint-disable-next-line import/no-default-export
export default {
displayName: 'test',
preset: 'ts-jest',
preset: 'ts-jest/presets/default-esm',
testMatch: ['<rootDir>/test/**/*.test.ts?(x)'],
// ESLint v8 では `pkg.exports` を利用したモジュールに依存しているが、jest は `pkg.exports` を解釈できないため、
// そのままだと jest がコケてしまう。そこで `moduleNameMapper` を使って無理やりモジュール名を解決している。
moduleNameMapper: {
'@eslint/eslintrc/universal': '@eslint/eslintrc/dist/eslintrc-universal.cjs',
// Map `./**/xxx.js` to `./**/xxx` (for ESM)
'^(\\.{1,2}/.*)\\.js$': '$1',
},
// for ESM
resolver: '<rootDir>/test/test-util/jest/resolver.cjs',
collectCoverageFrom: ['<rootDir>/src/**/*.{ts,tsx}', '!**/*.d.ts'],
globals: {
'ts-jest': {
tsconfig: 'tsconfig.test.json',
useESM: true,
},
},
};
17 changes: 17 additions & 0 deletions test/test-util/jest/resolver.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// ref: https://github.com/facebook/jest/issues/9771#issuecomment-974750103
const importResolver = require('enhanced-resolve').create.sync({
conditionNames: ['import', 'node', 'default'],
extensions: ['.js', '.json', '.node', '.ts'],
});
const requireResolver = require('enhanced-resolve').create.sync({
conditionNames: ['require', 'node', 'default'],
extensions: ['.js', '.json', '.node', '.ts'],
});

module.exports = function (request, options) {
let resolver = requireResolver;
if (options.conditions?.includes('import')) {
resolver = importResolver;
}
return resolver(options.basedir, request);
};

0 comments on commit 0e5caf8

Please sign in to comment.