尝试在NX (类型记录/角)中使用jsdom和Jest,我就会遇到TextEncoder和TextDecoder不存在的问题。无论我将jest 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"
},发布于 2022-02-06 17:40:36
我设法消除了错误,首先将全局对象强制给any,然后分配TextDecoder:
import { TextEncoder, TextDecoder } from "util";
(global as any).TextEncoder = TextEncoder;
(global as any).TextDecoder = TextDecoder;我知道这不是实现预期目标的最佳方法,而且通常被认为是错误的实践,但是,由于这只是Jest的测试,我认为这应该是可以的。
https://stackoverflow.com/questions/70808405
复制相似问题