尝试在 NX 存储库(打字稿/角度)中将 jsdom 与 Jest 一起使用,我遇到的问题是
TextEncoder
和 TextDecoder
不存在。无论我将笑话 testEnvironment
设置为 'jsdom'
还是 'node'
并且节点版本从 10 到 16),我都会得到相同的结果
因此,按照其他人发布的解决方案(谢谢!),我将它们从节点导入到我的
test-setup.ts
中,并将它们设置在节点全局对象上:
import 'jest-preset-angular/setup-jest'
import { TextEncoder, TextDecoder } from 'util';
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
这似乎适用于
TextEncoder
,但不适用于TextDecoder
:
libs/xplat/features/test-setup.ts:10:1 - error TS2322: Type 'typeof TextDecoder' is not assignable to type '{ new (label?: string | undefined, options?: TextDecoderOptions | undefined): TextDecoder; prototype: TextDecoder; }'.
The types of 'prototype.decode' are incompatible between these types.
Type '(input?: ArrayBufferView | ArrayBuffer | null | undefined, options?: { stream?: boolean | undefined; } | undefined) => string' is not assignable to type '(input?: BufferSource | undefined, options?: TextDecodeOptions | undefined) => string'.
Types of parameters 'input' and 'input' are incompatible.
Type 'BufferSource | undefined' is not assignable to type 'ArrayBufferView | ArrayBuffer | null | undefined'.
Type 'ArrayBufferView' is not assignable to type 'ArrayBufferView | ArrayBuffer | null | undefined'.
Type 'ArrayBufferView' is missing the following properties from type 'DataView': getFloat32, getFloat64, getInt8, getInt16, and 17 more.
10 global.TextDecoder = TextDecoder;
我应该使用不同的
TextDecoder
- 特别是,是否有一个以某种方式与 jest 的 jsdom 捆绑在一起,我只是不知道如何使用?
如果有帮助,这里有一些版本(来自我最近的
package.json
):
"devDependencies": {
"@angular-devkit/architect": "^0.1301.2",
"@angular-devkit/build-angular": "<=13.0.2",
...
"@nrwl/angular": "13.4.6",
"@nrwl/cli": "13.4.6",
...
"@nrwl/jest": "13.4.6",
...
"@types/core-js": "^2.5.5",
"@types/jest": "^27.0.2",
"@types/jsdom": "^16.2.14",
"@types/node": "14.14.33",
"@types/whatwg-url": "^8.2.1",
"@typescript-eslint/eslint-plugin": "~5.3.0",
"@typescript-eslint/parser": "~5.3.0",
...
"jest": "27.2.3",
"jest-jasmine2": "^27.4.6",
"jest-preset-angular": "11.0.0",
"jsdom": "^19.0.0",
"ng-mocks": "^12.5.1",
...
"ts-jest": "27.0.5",
"typescript": "~4.4.3",
"util": "^0.12.4",
"whatwg-url": "^11.0.0"
},
我设法通过首先将全局对象强制为任何然后分配 TextDecoder 来摆脱错误:
import { TextEncoder, TextDecoder } from "util";
(global as any).TextEncoder = TextEncoder;
(global as any).TextDecoder = TextDecoder;
我知道这不是实现预期目标的最佳方式,通常会被认为是不好的做法,但是,由于这只是为了 Jest 的测试,我认为应该没问题。
我可以通过这样做解决它:
import {TextDecoder as NodeTextDecoder} from 'util';
global.TextDecoder = NodeTextDecoder as typeof TextDecoder;
我认为问题来自于 TextDecoder 是全局 Typescript 类型,因此我们需要使用另一个名称。我断言节点 TextDecoder 到 TypeScript TextDecoder,我不确定这是否正确,但我认为它比任何其他都更安全。