[英]Typescript and NodeJS : ReferenceError : Module is not defined
[英]"ReferenceError: structuredClone is not defined" using jest with nodejs & typescript
我在一个使用 typescript 的简单 NodeJS 应用程序中jest
地运行测试。 我的测试抛出一个错误: ReferenceError: structuredClone is not defined
。
我没有收到任何 linter 错误,并且代码可以正常编译。
const variableForValidation = structuredClone(variableForValidationUncloned);
package.json:
"dependencies": {
...
},
"devDependencies": {
"@types/jest": "^29.0.0",
"@types/node": "^18.7.15",
"@typescript-eslint/eslint-plugin": "^5.36.1",
"@typescript-eslint/parser": "^5.36.1",
"eslint": "^8.23.0",
"jest": "^28.0.1",
"nodemon": "^2.0.19",
"serverless-plugin-typescript": "^2.1.2",
"ts-jest": "^28.0.8",
"ts-node": "^10.9.1",
"typescript": "^4.8.2"
}
这个 github 问题向我表明问题已经解决: https://github.com/facebook/jest/issues/12628 - 或者我误解了?
我见过类似的堆栈问题,但使用摩卡: 摩卡不识别结构化克隆未定义
我想不通,所以我设置了自己的全局:
// globals.ts
if(!global.structuredClone){
global.structuredClone = function structuredClone(objectToClone: any) {
const stringified = JSON.stringify(objectToClone);
const parsed = JSON.parse(stringified);
return parsed;
}
}
// entry point of app, eg index.ts:
import './globals.ts'
// ...
我认为这可能是因为我的tsconfig
中的target
是在添加结构化克隆之前将我的 typescript 文件转换为 javascript/node 版本?
对于同样的错误,在测试文件中使用下面的代码为我解决了这个问题。
global.structuredClone = (val) => JSON.parse(JSON.stringify(val))
在节点 17 中添加了structuredClone
克隆。
如果您无法更新, JSON
hack(字符串化然后解析)可以工作,但有一些可能与您相关的缺点:
- 递归数据结构: JSON.stringify() 当你给它一个递归数据结构时会抛出。 在使用链表或树时,这很容易发生。
- 内置类型:JSON.stringify() 如果值包含其他 JS 内置类型,如 Map、Set、Date、RegExp 或 ArrayBuffer,将抛出。
- 函数: JSON.stringify() 将悄悄地丢弃函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.