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

Jest+Node.js+TypeScript测试报错:structuredClone未定义

解决Jest测试中structuredClone is not defined错误

问题原因

structuredClone是Node.js 17.0.0及以上版本才原生支持的API,你的代码编译正常是因为@types/node@18.x已经包含了该API的类型定义,但Jest运行时的Node环境版本可能低于17,或者Jest/ts-jest的配置未正确匹配目标环境。

解决方法

方法1:升级Jest及相关依赖

Jest 29+对Node.js 18的支持更完善,同时需要同步升级ts-jest和@types/jest版本,确保版本兼容:

  • 卸载旧依赖:
    npm uninstall jest ts-jest @types/jest
    
  • 安装兼容的最新版本:
    npm install -D jest@^29 ts-jest@^29 @types/jest@^29
    

方法2:调整Jest和TypeScript配置(无需升级)

  1. 在tsconfig.json中设置目标版本为ES2022(该版本包含structuredClone):
    {
      "compilerOptions": {
        "target": "ES2022",
        // 其他配置...
      }
    }
    
  2. 在jest.config.js中指定测试环境为Node,并同步TypeScript目标版本:
    module.exports = {
      preset: 'ts-jest',
      testEnvironment: 'node',
      globals: {
        'ts-jest': {
          tsconfig: {
            target: 'ES2022'
          }
        }
      },
      // 如果使用Jest 28.1.0+,还可以直接指定Node版本:
      testEnvironmentOptions: {
        nodeVersion: '18'
      }
    };
    

方法3:手动添加Polyfill

如果上述方法无法生效,可以为测试环境添加structuredClone的polyfill:

  1. 安装core-js-pure:
    npm install -D core-js-pure
    
  2. 在Jest的setupFilesAfterEnv指定的文件(比如jest.setup.js)中添加全局polyfill:
    global.structuredClone = require('core-js-pure/actual/structured-clone');
    
  3. 在jest.config.js中配置setup文件:
    module.exports = {
      // 其他配置...
      setupFilesAfterEnv: ['./jest.setup.js']
    };
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:24:28