-
Notifications
You must be signed in to change notification settings - Fork 451
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
import.meta not allowed #1174
Comments
Hi, I see your jest.config.js doesn't have preset: 'ts-jest'. Would you please try adding that in your jest.config.js ? More about installation and configuration can be found at online documentation |
I'm having the same issue as @ejmartin504.
Using preset ts-jest doesn't help. Docs says
but I have
set in my tsconfig.json. It just seems that ts-jest doesn't honour my ts settings. @ejmartin504 Did you find a way around this? |
Stuff happens around here, I might need to debug this to understand what's going on: https://github.com/kulshekhar/ts-jest/blob/master/src/config/config-set.ts#L712 |
This is the problem I think: ts-jest/src/config/config-set.ts Lines 558 to 562 in 2fabdb1
I'm guessing here, but since I want to use node with --experimental-modules and not use babel, this messes up for me. My ts-config to output esm is overwritten because I haven't attached any babel transpilation? |
Hi, I think I found something related to this in here. Would you guys that solution ? I think indeed you need to ask babel-jest to transform into commonjs. |
Yes, because when there is no babel and jest expects |
close as not |
import.meta is only valid for esm. Jest is working on supporting it jestjs/jest#9430 . I think now ts-jest can unforce commonjs module in internal code |
I'm still struggling with this. I had forgotten about this issue and started to create a repro case for jestjs/jest#9430. But I couldn't get to the same issue as my production code in the repro until I found this issue again and realized I needed babel to get pass that. My setup is just:
And I'm trying to use
Here's a pretty small repro: https://github.com/hedefalk/jest-esm-ts-issue Any help on workaround is highly appreciated. As I understand it, its basically not possible to use ts-jest with esm. I'm having to run a separate tsc and test on the output for now. |
at the moment, Unfortunately there is no workaround now :) I still don't know what is the suitable time to remove that hardcoded condition, maybe once jestjs/jest#9430 is completed. For now, imo A PR is welcome for that new option :) |
I'm not sure I follow entirely. I tried just removing that override condition entirely in my node_modules/ts-jest/dist/config-set.js: console.log('not doing any module kind override')
// if (!this.tsJest.babelConfig) {
// options.module = this.compilerModule.ModuleKind.CommonJS;
// } But still leaving the babel config around, I still get that issue:
Maybe my babel config is all messed up, dunno, but I can't seem to do without it… |
Oh, sorry, its not the same issue of course, a later one… |
by removing that condition, it only allows There are some discussions about how transformers pass compiled out to Discussion about extension is here jestjs/jest#9860 . Also related to the error you got |
@ahnpnl Yeah, thanks, realized after posting. I think I should report over there. It's supposed to look at the package.json and if type=module it should be a ESM, right? |
I just put a question here jestjs/jest#9860 (comment) In general, my opinions are:
The main concern is what kind of file extensions that |
@ahnpnl Thx for the explanation! Mostly note to self, just double checked. I could finally run my tests by monkey patching to always return true here: But then I had @babel/plugin-syntax-import-meta in my babel for some reason which transpiled it into require so it broke anyways:
So had to remove that one, but after that I could finally run it:
|
Nice 👍 that means it is possible but just need some clarifications from jest to implement the correct way for ts-jest. Or ts-jest can use the simplest approach by giving compiled file with mjs/cjs depending on target under a new config option “experimentalEsm”. This will give ts-jest users opportunities to test esm. Once getting the final recommendation from jest, the implementation can change. |
Trying to be a good citizen and also I'd hate to maintain a monkey patching sed/awk :) Started here: master...hedefalk:master I was hoping to be able to just do the option in ts-jest and that outputting a .mjs extension would be enough. However, the logic here is looking at the actual input files: which in our case is |
If I understood it right, you just need to add the following to package.json:
And then run it like this: |
Is there a working solution for this problem? I'm unable to write tests for my codebase because of this and can't seem to find a working fix. Also using vite like mentioned in the linked issue above here. |
The only way to use |
@ahnpnl thanks for the info. This uses Jest v27 though and I'm on v26. I did find a workaround albeit a bit verbose and not ideal but my tests are running now. I just provided the dependency that contains |
You can always isolate es6 only code without changing jest configurations, presets, transformers and experimental features usage. Isolate file with
and mock this import in the setup file via
|
I'm getting jest.config.cjs const ts = require("typescript");
const { pathsToModuleNameMapper } = require("ts-jest/utils");
const { config: tsconfig } = ts.readConfigFile(
"./tsconfig.json",
ts.sys.readFile,
);
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
const config = {
testEnvironment: "jsdom",
transform: {
"^.+\\.tsx?$": ["ts-jest"],
},
moduleNameMapper: pathsToModuleNameMapper(
tsconfig.compilerOptions.paths ?? {},
{ prefix: "<rootDir>" },
),
extensionsToTreatAsEsm: [".ts", ".tsx"],
globals: {
"ts-jest": {
useESM: true,
},
},
};
module.exports = config; tsconfig.json: {
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
// ...
},
} Is there any solution so far? Thanks in advance! |
Have you read and followed all steps in the ESM instructions? I had a similar problem, and it turned out that I had missed part of the setup because I had mistaken the first link as "documentation only" and skipped it, but the page actually contains some important steps. TL;DR:
|
hi could you please help to check what is not correct in my configuration? I also use this mock method, but it seems not work...
the log is printed as expected, but the execution will still go to the function |
What exactly did you do to resolve it?
|
I ran into the same issue with Jest and TypeScript not recognizing
After that was done I was able to have my tests pass successfully while using |
@annalyncs |
Believe it or not, this worked: Create a commonjs file, like "currentPath.cjs", Inside it put something like:
In your module use:
|
Below code will help to go away import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext': return { |
@kulkarnipradnyas Could you clarify where the code below goes?
|
Yes i have uodated in jest.config, tsconfig and babel.config.js file.I have highlighted file names in above solution.
|
This package solves the problem https://github.com/ThomZz/ts-jest-mock-import-meta |
I don't get why this is closed. Currently having this issue. The only way to get around was to use @Yankovsky advice. All of the other ones didn't work. |
By "solving a problem" you mean a need to manually mock files with |
@ivan-kleshnin it is an external dep of your module just like any other import. Seems natural to me to mock it in the test. |
I end up using babel instead of ts-jest because of this… |
Import meta only works when running Jest in ESM mode. There are some example projects with base configuration to work with ESM, see https://github.com/kulshekhar/ts-jest/tree/main/examples Also, please take a look at documentation https://kulshekhar.github.io/ts-jest/docs/guides/esm-support |
For anyone else that finds this through a web search, my solution to this problem was to migrate to |
any updates on the recommended approach to deal with this issue? |
I was tempted to use Vitest after some time looking for a solution for this issue, but it seems it's slower than jest in the actual version so I'm also searching for the best approach for solving it |
this is the only solution worked for me. its year 2023. almost 3 years have passed and there seems to be no proper solution for this problem. why this issue is closed? |
Perhaps you can make a reproduce scenario with one of the exampe repos https://github.com/kulshekhar/ts-jest/tree/main/examples? Note that |
Still looking for a good approach, not a hack solution. // babel.config.cjs
module.exports = {
presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-typescript"],
plugins: ["babel-plugin-transform-vite-meta-env"],
} // jest.config.cjs
module.exports = {
testEnvironment: "node",
} test file // index.spec.ts
describe("zhiEnv", () => {
const NOT_EXIST_KEY = "NOT_EXIST_KEY"
it("test env", () => {
const env = new Env(import.meta.env)
expect(env.getEnv(EnvConstants.NODE_ENV_KEY)).toEqual("test")
})
}) package to install
result |
Issue :
In a node project, I'm using
import.meta.url
to get __dirname like so:my tsconfig:
Running
tsc
gives me no issues, but runningjest
results in this error:I have tried a few different places for the
tsconfig
and have even tried to use a separate config forts-jest
, but I get this error every time.Expected behavior :
Normal compilation and successful test.
Debug log:
log file content
Minimal repo :
https://github.com/ejmartin504/test-ts
The text was updated successfully, but these errors were encountered: