如果node的util.TextDecoder类型不匹配,如何在jest中为jsdom设置global.TextDecoder?

mrphzbgm  于 6个月前  发布在  Jest
关注(0)|答案(2)|浏览(85)

尝试在NX repo(typescript/angular)中使用jsdom和Jest,我得到的问题是TextEncoderTextDecoder不存在。无论我将jest testEnvironment设置为'jsdom'还是'node',以及节点版本从10到16,我都得到相同的结果)
因此,根据其他人发布的解决方案(谢谢!),我将它们导入到我的test-setup.ts from node中,并将它们设置在node全局对象上:

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"
  },

yizd12fk

yizd12fk1#

我设法摆脱了错误,首先强制全局对象为任何,然后分配TextDecoder:

import { TextEncoder, TextDecoder } from "util";
(global as any).TextEncoder = TextEncoder;
(global as any).TextDecoder = TextDecoder;

字符串
我知道这不是实现预期目标的最佳方式,通常会被认为是不好的做法,但是,因为这只是为了Jest的测试,我认为这应该是好的。

ohtdti5x

ohtdti5x2#

我可以通过这样做来解决它:

import {TextDecoder as NodeTextDecoder} from 'util';

global.TextDecoder = NodeTextDecoder as typeof TextDecoder;

字符串
我认为问题来自TextDecoder是一个全局Typescript类型,因此我们需要使用另一个名称。我Assert节点TextDecoder到TypeScript TextDecoder,我不确定这是否正确,但我认为它比任何都更安全。

相关问题