在 ES2020/ESNEXT TS 项目中使用 ts-jest 时,Jest 测试失败

ken*_*ken 12 typescript jestjs

我有一个 VueJS 项目,它使用 ViteJS 进行转译(这工作正常),显然,当涉及 ViteJS 时,生成的输出是本机 ES 模块,但对于 Jest 测试,我仍然使用ts-jest和我正常的旧 Jest 配置:

jest.config.ts

import { resolve } from "path";
import type { Config } from "@jest/types";

const config: Config.InitialOptions = {
  verbose: true,
  testEnvironment: "jsdom",
  // roots: ["tests", "src"],
  transform: {
    "^.+\\.tsx?$": "ts-jest",
  },
  testPathIgnorePatterns: ["/node_modules/"],
  moduleNameMapper: {
    "^[/]{0,1}~/(.*)$": resolve(process.cwd(), "src", "$1"),
  },
  testMatch: ["**/?(*[-.])+(spec|test).ts"],
  setupFilesAfterEnv: ["jest-extended"],
};

export default config;
Run Code Online (Sandbox Code Playgroud)

现在我突然收到这个错误:

错误信息

现在这个错误似乎集中在新的import.meta元属性上。这是一个新属性,但我的印象是使用“ES2020”和“ESNEXT”作为目标将允许我使用它。事实上,Vite/Rollup 的转译没有问题,vs-code 也没有给我任何警告,但在 Jest、ts-jest 和 Typescript 之间,某些东西没有给 Jest 测试运行程序提供错误的“目标”(我的 tsconfig.json)文件正确)。

现在我发誓,即使有这个参考,它也能工作,import.meta不知怎的,现在却不行了。我不确定我的 ENV 发生了什么变化。可能是一个稍微新的节点版本(我当前正在使用14.17.6)?可能是 Typescript 的一个稍微新的版本(4.4.2我目前正在使用的)。

无论如何,有谁知道我怎样才能克服这个问题?


笔记:

  • 我的 tsconfig.json 内容如下:
{
  "compilerOptions": {
    "module": "ES2020",
    "target": "ESNext",
    "lib": ["DOM", "ESNext"],
    "strict": true,
    "esModuleInterop": true,
    "incremental": true,
    "skipLibCheck": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "noUnusedLocals": true,
    "strictNullChecks": true,
    "forceConsistentCasingInFileNames": true,

    "baseUrl": ".",
    "declaration": true,
    "outDir": "dist",

    "paths": {
      "~/*": ["src/*"]
    },

  },
  "include": ["src", "test"],
  "exclude": ["dist", "node_modules"]
}
Run Code Online (Sandbox Code Playgroud)

小智 1

Jest 库似乎仍然存在问题。

https://github.com/facebook/jest/issues/12952

我们强制执行 CJS,也许我们应该对此进行调整。不幸的是,这需要使用加载器,不过...很想找到一种让 Jest 只要求 ts-node 为我们加载配置的好方法,而不关心它是用什么风格的模块系统编写的

https://github.com/kulshekhar/ts-jest/issues/3648#issuecomment-1160480989

请注意,ts-jest 不处理 jest.config.ts。jest.config.ts 由 ts-node 处理。

当您将 console.log(import.meta) 放入 jest.config.ts 中时,ts-node 会将配置文件转换为 CJS 或 ESM 语法,然后 jest 将处理 jest.config.ts 文件。你的问题不在ts-jest的范围内。