Skip to content

Instantly share code, notes, and snippets.

@thynson
Last active September 23, 2021 15:48
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 thynson/6b3c467506ab385da1df006d046c241c to your computer and use it in GitHub Desktop.
Save thynson/6b3c467506ab385da1df006d046c241c to your computer and use it in GitHub Desktop.
Jest custom resolver not work in globalSetup
import {MyClass} from './test-file';
test('stub', async () => {
await new MyClass().function();
});
const enhancedResolve = require('enhanced-resolve');
module.exports = function (request, options) {
if (request.startsWith('./test-file')) {
console.log('this line shall be printed twice');
}
const resolver = enhancedResolve.create.sync({
conditionNames: ['node'].concat(options.conditions || []),
fullySpecified: false,
extensions: [".js", ".json", ".node", ".ts", ".tsx"]
})
if (options.basedir.startsWith(__dirname)
&& options.basedir.indexOf('/node_modules/') < 0) {
if ((options.conditions || []).indexOf('import') >= 0 && request.startsWith('.') && !/.[cm]?js$/.test(request)) {
throw new Error('File extensions cannot be omitted when importing a file from ESM module')
}
request = request.replace(/\.js$/, '');
}
return resolver(options.basedir, request);
};
module.exports = {
// testRegex,
testEnvironment: 'node',
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
resolver: './jest-resolve.cjs',
//extensionsToTreatAsEsm: ['.ts', '.tsx'],
// setupFiles: [__dirname + '/jest-setup.cjs'],
globalSetup: '<rootDir>/setup.ts',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.json',
diagnostics: 'pretty',
// useESM: true,
},
},
};
{
"name": "jest-bug",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"@types/jest": "^27.0.1",
"enhanced-resolve": "^5.8.3",
"jest": "^27.2.1",
"ts-jest": "^27.0.5",
"ts-node": "^10.2.1",
"typescript": "^4.4.3"
},
"dependencies": {
"reflect-metadata": "^0.1.13"
}
}
import { MyClass } from './test-file';
export default async () => {
await new MyClass().function();
}
export class MyClass {
async function() {
return new Promise(setImmediate);
}
}
{
"compilerOptions": {
"target": "es2018",
"moduleResolution": "node",
"esModuleInterop": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictNullChecks": true,
"noUncheckedIndexedAccess": true,
"useDefineForClassFields": true,
"strict": true,
"alwaysStrict": true,
"outDir": "lib/",
"noEmitHelpers": true,
"importHelpers": true,
"incremental": true,
"sourceMap": true,
"declaration": true,
"declarationMap": true,
"skipLibCheck": true,
"lib": [
"es2020"
],
"module": "commonjs",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"jsx": "react"
},
"exclude": [
"node_modules",
"dist"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment