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配置(无需升级)
- 在
tsconfig.json中设置目标版本为ES2022(该版本包含structuredClone):{ "compilerOptions": { "target": "ES2022", // 其他配置... } } - 在
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:
- 安装core-js-pure:
npm install -D core-js-pure - 在Jest的
setupFilesAfterEnv指定的文件(比如jest.setup.js)中添加全局polyfill:global.structuredClone = require('core-js-pure/actual/structured-clone'); - 在
jest.config.js中配置setup文件:module.exports = { // 其他配置... setupFilesAfterEnv: ['./jest.setup.js'] };
内容的提问来源于stack exchange,提问作者JimmyTheCode
相关产品推荐
相关产品推荐

