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

Jest测试Mock含import.meta的工具函数报错,求解决方案

解决Jest测试中import.meta导致的模块版本错误问题

问题重现

工具函数通过import.meta.url解析文件路径,在Jest测试阶段触发以下错误:

The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022'...etc

相关代码如下:

工具函数(readFileUtil.ts)

import { fileURLToPath } from 'url';
import path from 'path';
import fs from 'fs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export async function readFile(fileName: string){
    try {
     const data = await fs.promises.readFile(fileName, 'utf8')
     return data
    } catch (err) {
      console.log(err);
    }
 }

业务代码

import readFileUtils from '../file-utils'
import dataProcessor from '../data/processor'

async function processData(fileName:string){
   const data = await readFileUtils.readFile(fileName)
   // 后续数据处理逻辑
}  

Jest测试代码

import readFileUtils from '../file-utils'
import dataProcessor from '../data/processor'

jest.mock('../file-utils') 
describe('Data Processing suite', () => {
    const fileName = 'resources/data.xml'
    it('should process data correctly', async () => {
        await processData(fileName)
        // 测试断言逻辑
    })
})

解决方案

1. 配置ts-jest的AST转换器

在jest.config.js(或jest.config.ts)中,通过ts-jest的AST转换器处理import.meta,确保已安装ts-jest-mock-import-meta依赖:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        diagnostics: {
          ignoreCodes: [1343] // 忽略import.meta的类型诊断错误
        },
        astTransformers: {
          before: ['ts-jest-mock-import-meta']
        }
      }
    ]
  }
}

2. 确保TypeScript配置匹配

修改tsconfig.json(或单独的tsconfig.test.json)的编译选项,指定符合要求的模块版本:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ES2020",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

如果使用单独的测试配置文件,在Jest配置中指定:

module.exports = {
  // ...其他配置
  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.test.json'
    }
  }
}

3. 手动Mock import.meta

如果上述方法无效,可在测试文件顶部或全局setup文件中手动Mockimport.meta.url:

// 测试文件顶部
Object.defineProperty(import.meta, 'url', {
  value: 'file:///mock/path/to/file-utils.ts'
});

或者在jest.setup.js中全局设置:

global.import.meta = { url: 'file:///mock/global/path' };

4. 调整路径获取逻辑(备选)

若不想依赖import.meta,可改用Node.js的URLAPI替代(效果一致):

// readFileUtil.ts
import path from 'path';
import fs from 'fs';

// 直接通过URL解析路径,避免显式赋值__filename
const __dirname = path.dirname(new URL(import.meta.url).pathname);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:10:18