jest: [Bug]: jest ts-node ignores provided tsconfig.json

Version

28.0.5

Steps to reproduce

Create valid jest.config.ts file wit the next content:

import { InitialOptionsTsJest } from 'ts-jest'
import path from 'path'

console.log(import.meta)

const jestOptions: InitialOptionsTsJest = {
    preset: 'ts-jest/presets/default-esm',
    rootDir: './some_root',
    testMatch: [ '**/*.test.ts' ],
    extensionsToTreatAsEsm: ['.ts'],
    moduleNameMapper: {
        '^(\\.{1,2}/.*)\\.js$': '$1'
    },
    globals: {
        'ts-jest': {
            useESM: true,
            tsconfig: path.join(process.cwd(), 'tsconfig.json')
        }
    }
}

export default jestOptions

Note console.log(import.meta)

Create valid tsconfig.json file:

{
    "compilerOptions": {
	"target": "esnext",
        "module": "esnext",
	"moduleResolution": "node",
        "allowJs": true,
	"esModuleInterop": true,
        "strict": true,
	"skipLibCheck": true,
        "declaration": true,
        "allowSyntheticDefaultImports": true,
        "isolatedModules": true
    }
}

run npx jest

Expected behavior

No TS errors

Actual behavior

Error: Jest: Failed to parse the TypeScript config file ./some_proj/jest.config.ts
  TSError: ⨯ Unable to compile TypeScript:
jest.config.ts:55:13 - error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'.

console.log(import.meta)
               ~~~~~~~~~~~

    at readConfigFileAndSetRootDir (/some_proj/node_modules/jest-config/build/readConfigFileAndSetRootDir.js:136:13)
    at async readConfig (/some_proj/node_modules/jest-config/build/index.js:216:18)
    at async readConfigs (/some_proj/node_modules/jest-config/build/index.js:404:26)
    at async runCLI (/some_proj/node_modules/@jest/core/build/cli/index.js:140:59)
    at async Object.run (/some_proj/node_modules/jest-cli/build/cli/index.js:155:37)

Additional context

No response

Environment

System:
  OS: Linux 5.17.12-100.fc34.x86_64
  CPU: (8) arm64

Binaries:
  Node: 16.15.0
  npm: 7.20.0

npmPackages:
  "jest": "28.1.0",
  "ts-jest": "^28.0.5"

Stack overflow

There is a question on stackoverflow been posted 9 months ago still not answered…

TS Jest

issue on git

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 13
  • Comments: 42 (6 by maintainers)

Most upvoted comments

srsly wtf

Bump. Not stale. Ffs.

So is there any workaround for this? This is the only blocker I have for migrating my code to ESM from CJS.

This seems to be rather a limitation in jest. I’m trying to port my mocha-based project to jest as I had thought it might have fewer issues with TypeScript and modules; but apparently not. Sometimes I wonder if anyone uses typescript and ECMAScript modules for anything as nothing seems to work; I’ve been on a multi-hour Google/SO/Github issue journey and nobody seems to have solved this

I don’t use it specifically in the jest.config.ts file, but my project does use it in the globalSetup.ts file which has the same issue.

Issue still present

Issue still present

The year is 2056 and jest still doesn’t support the future.

I don’t have a solution, just wanted to add a snarky comment because this has wasted 2-3 hours of my time.

That makes 2 of us 🙌🏼 Given the speed at which this is being resolved, I’m moving to Vitest

The year is 2056 and jest still doesn’t support the future.

I don’t have a solution, just wanted to add a snarky comment because this has wasted 2-3 hours of my time.

Hey peeps,

My teammate @macmv came up with a work around for this using jest transformers.

Feel free to use this code:

const tsJest = require("ts-jest").default;

module.exports = {
  createTransformer(config) {
    const transformer = tsJest.createTransformer(config);
    const tsProcess = transformer.process;
    transformer.process = (sourceText, ...rest) => {
      sourceText = sourceText.replaceAll("import.meta.env", "({} as any)");
      return tsProcess(sourceText, ...rest);
    };
    return transformer;
  },
};

The other nifty thing about this is you could extend it to install some kind of mock object instead of ({} as any) for example { taco: "tuesday", pizza: "friday" }.

Enjoy!

I think there’s some confusion because the tsconfig used to compile jest.config.ts, before launching the test runner, is not necessarily the same tsconfig used by the ts-jest transformer to compile the TS code under test.

I don’t write my Jest config in TS – it works fine in JS with type annotation comment directives – but for those who do, is there really a use-case for consuming import.meta while configuring Jest (i.e., specifically in jest.config.ts)?

As far as consuming import.meta in the code under test, I believe that should fall into the purview of ts-jest – they punted over here specifically because you’re trying to refer to it in the config file, before ts-jest actually does anything.

ETA: actually I don’t think there is a problem on the ts-jest side. I just found https://github.com/kulshekhar/ts-jest/issues/3888 which links to this handy example, where the user is successfully running a test that uses import.meta, using ts-jest/presets/default-esm. So, bottom line, this issue is only about import.meta in jest.config.ts, specifically, and if you want to use import.meta in your code and/or tests, that already works. (Again, if you are trying to use import.meta in jest.config.ts, I would be really curious to know why.)

Yeah, this isn’t currently possible - see https://github.com/facebook/jest/issues/11453#issuecomment-1040424443. In #12397 we enforce CJS, might be we should tweak this. It’s unfortunate this requires using a loader, tho… Would love to figure out a good way for Jest to just ask ts-node to load the config for us without caring about what flavour of module system it’s written in