You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Jest测试ECMAScript模块时遇环境配置错误,求解决方案

问题:Jest测试ECMAScript模块时出现验证错误

执行Jest测试ESM模块时,遇到以下验证错误:

● Validation Error:

  Test environment node --experimental-vm-modules node_modules/jest/bin/jest.js cannot be found. Make sure the testEnvironment configuration option points to an existing node module.

用户配置与项目结构

jest.config.js

module.exports = {
  testEnvironment: 'node --experimental-vm-modules node_modules/jest/bin/jest.js',
  testMatch: [
    '**/tests/**/*.test.mjs'
  ],
  transform: {},
  transformIgnorePatterns: [
    '/node_modules/',
    '\\.pnp\\.[^\\/]+$'
  ],
  moduleFileExtensions: [
    'js',
    'mjs',
    'json',
    'node'
  ],
  globals: {
    'ts-jest': {
      useESM: true
    }
  }
};

package.json

{
  "type": "module",
  "dependencies": {
    "mindsdb-js-sdk": "^2.2.2"
  },
  "devDependencies": {
    "jest": "^29.6.3"
  },
  "scripts": {
    "test": "jest"
  }
}

项目结构

my-project/
├── config/
│   └── config.js
├── node_modules/
├── src/
│   └── myModule.mjs
├── jest.config.js
├── package.json
├── package-lock.json
└── tests/
    ├── myModule.test.mjs

错误原因与修正方案

核心错误点

testEnvironment配置错误:该字段用于指定测试环境的Node模块名称(如node或jsdom),你错误地将Node启动参数和Jest命令路径填到了这里,导致Jest无法识别有效的测试环境模块。

具体修正步骤

  1. 修正jest.config.js

    • 将testEnvironment改为标准值'node'
    • 移除无用的ts-jest全局配置(未使用TypeScript)
    • 最终配置如下:
      module.exports = {
        testEnvironment: 'node',
        testMatch: [
          '**/tests/**/*.test.mjs'
        ],
        transform: {},
        transformIgnorePatterns: [
          '/node_modules/',
          '\\.pnp\\.[^\\/]+$'
        ],
        moduleFileExtensions: [
          'js',
          'mjs',
          'json',
          'node'
        ]
      };
      
  2. 修改package.json的test脚本
    Jest的ESM实验性支持需要Node启用--experimental-vm-modules参数,需将该参数添加到测试命令中:

    {
      "scripts": {
        "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
      }
    }
    
  3. 验证配置
    确保测试文件和被测文件的扩展名正确(.mjs),且package.json中已设置"type": "module",这些你当前的配置已经符合要求。

完成以上修改后,即可正常运行Jest测试ESM模块。

内容的提问来源于stack exchange,提问作者Minura Punchihewa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 21:27:28