簡體   English   中英

“ReferenceError:未定義結構化克隆”使用 nodejs 和 typescript 開玩笑

[英]"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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM