Jest.js 测试套件无法运行导入, meta.env.VITE_*

v440hwme  于 2022-12-25  发布在  Jest
关注(0)|答案(2)|浏览(315)

在我的代码中添加环境变量import.meta.env.VITE_*之后,使用vue-test-utils进行的测试开始失败,错误如下:

Jest suite failed to run
error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'.

我已经搜索了一些可用的修复程序,但到目前为止还没有工作。

    • 编辑**

jest.config.js文件:

module.exports = {
  preset: "ts-jest",
  globals: {},
  testEnvironment: "jsdom",
  transform: {
    "^.+\\.vue$": "@vue/vue3-jest",
    "^.+\\js$": "babel-jest"
  },
  moduleFileExtensions: ["vue", "js", "json", "jsx", "ts", "tsx", "node"],
  moduleNameMapper: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
      "<rootDir>/tests/unit/__mocks__/fileMock.js",
    "^@/(.*)$": "<rootDir>/src/$1"
  }
}

tsconfig.json文件:

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": ["env.d.ts", "src/**/*", "src/**/*.vue", "tests"],
  "compilerOptions": {
    "module": "esnext",
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },

  "references": [
    {
      "path": "./tsconfig.vite-config.json"
    }
  ]
}

包括module: "esnext"时,显示以下警告,错误仍然存在。
验证警告:
找到值为"commonjs"的未知选项"module"。这可能是键入错误。修复该错误将删除此消息。
配置文档:https://jestjs.io/docs/configuration

b4qexyjb

b4qexyjb1#

经过大量的研究,我终于破案了.
我必须安装vite-plugin-environmentbabel-plugin-transform-import-meta库并进行以下设置:

    • 巴别塔配置js**
module.exports = {
  ...
  plugins: ["babel-plugin-transform-import-meta"]
}
    • 曾菲·杰森**
{
  ...
  "compilerOptions": {
    "module": "esnext",
    ...
    "types": [
      "node"
    ]
  },
  ...
}
    • 维生素配置ts**
...
import EnvironmentPlugin from "vite-plugin-environment"
...
export default defineConfig({
  plugins: [..., EnvironmentPlugin("all")],
  ...
})

同时将import.meta.env.*更改为process.env.*

o4hqfura

o4hqfura2#

就我个人而言,我通过一个文件(src/constants.ts或src/constants.js)路由所有的import.meta.env

// src/constants.(js|ts)...

const {
  MODE: ENVIRONMENT,
} = import.meta.env;

export {
  ENVIRONMENT
};

然后在我的jest测试中,我只是模拟常量文件:

// example.test.(js|ts)
jest.mock('src/constants', () => ({
  ENVIRONMENT: 'development',
}));

恕我直言,这是更好的,因为你可能会想嘲笑的价值无论如何。

相关问题