reactjs '参考错误:运行“React脚本test --env=jsdom”时,未定义TextEncoder

iezvtpos  于 2023-02-04  发布在  React
关注(0)|答案(9)|浏览(219)

我在应用程序中使用TensorFlow编码器。当应用程序运行时,它在浏览器中工作正常,但在测试它构建的代码时遇到问题:

$ npx react-scripts test --env=jsdom
FAIL  src/App.test.js
  ● Test suite failed to run

    ReferenceError: TextEncoder is not defined

      16 | import TextField from '@material-ui/core/TextField';
      17 | import Typography from '@material-ui/core/Typography';
    > 18 | import * as mobilenet from '@tensorflow-models/mobilenet';
         | ^
      19 | import * as UniversalSentenceEncoder from '@tensorflow-models/universal-sentence-encoder';
      20 | import * as tf from '@tensorflow/tfjs';
      21 | import axios from 'axios';

      at new PlatformBrowser (node_modules/@tensorflow/tfjs-core/src/platforms/platform_browser.ts:26:28)
      at Object.<anonymous> (node_modules/@tensorflow/tfjs-core/src/platforms/platform_browser.ts:50:30)
      at Object.<anonymous> (node_modules/@tensorflow/tfjs-core/src/index.ts:29:1)
      at Object.<anonymous> (node_modules/@tensorflow/tfjs-converter/src/executor/graph_model.ts:18:1)
      at Object.<anonymous> (node_modules/@tensorflow/tfjs-converter/src/index.ts:17:1)
      at Object.<anonymous> (node_modules/@tensorflow-models/mobilenet/dist/index.js:38:14)
      at Object.<anonymous> (src/components/model.js:18:1)
      at Object.<anonymous> (src/App.js:8:1)
      at Object.<anonymous> (src/App.test.js:3:1)

我想摆脱这个错误。我已经尝试使用'text-encoding'包,但我不知道如何在导入发生之前正确定义TextEncoder。
也许我可以为--env设置一个不同的选项?
我得到了同样的错误没有--env=jsdom。我相信我添加了它后,得到类似类型的未定义的错误,它纠正了一个问题。
下面是我的测试:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});

因此,设置--env=node也不起作用,因为:ReferenceError: document is not defined.

eqzww0vc

eqzww0vc1#

jsdom似乎没有在DOM的global中定义TextEncoder,所以可以用node.js中的一个来填充它。
测试/自定义测试环境js:

const Environment = require('jest-environment-jsdom');

/**
 * A custom environment to set the TextEncoder that is required by TensorFlow.js.
 */
module.exports = class CustomTestEnvironment extends Environment {
    async setup() {
        await super.setup();
        if (typeof this.global.TextEncoder === 'undefined') {
            const { TextEncoder } = require('util');
            this.global.TextEncoder = TextEncoder;
        }
    }
}

npx react-scripts test --env=./test/custom-test-env.js

t3irkdon

t3irkdon2#

我的Node.Js项目也出现了同样的错误。出于测试目的,我在那里使用了jest。因此,以下步骤解决了我的问题
step-1:在项目的根文件夹上添加名为jest.config.js的文件
step-2:在jest.config文件中添加以下行:

module.exports = {
        testEnvironment: "node"
    };
zaq34kh6

zaq34kh63#

谢谢你的回答。一个看起来更简单的格式,至少在testEnvironment: 'jsdom'中是这样的:

setupFiles: [`<rootDir>/jest-shim.js`],

jest-shim.js:

import { ArrayBuffer, TextDecoder, TextEncoder, Uint8Array } from 'util';

global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
global.ArrayBuffer = ArrayBuffer;
global.Uint8Array = Uint8Array;
lsmepo6l

lsmepo6l4#

我在使用mongodb的时候遇到过这个问题,我使用了@Phoenix的解决方案,做了一点改动。
首先,我使用jest-environment-node而不是jest-environment-jsdom

const NodeEnvironment = require('jest-environment-node');

// A custom environment to set the TextEncoder that is required by mongodb.
module.exports = class CustomTestEnvironment extends NodeEnvironment {
  async setup() {
    await super.setup();
    if (typeof this.global.TextEncoder === 'undefined') {
      const { TextEncoder } = require('util');
      this.global.TextEncoder = TextEncoder;
    }
  }
}

然后我在jest configs中为所有测试添加了环境,如Cava在注解中所述:

// package.json
{
  ...
  "jest": {
    ...
    "testEnvironment": "<rootDir>/tests/custom-test-env.js"
  }
  ...
}
vu8f3i0k

vu8f3i0k5#

根据最新的jest v28(https://jestjs.io/docs/upgrading-to-jest28)和react 18我不得不修改了一点脚本
所以我的preSetup.js

const Environment = require('jest-environment-jsdom-global');
/**
 * A custom environment to set the TextEncoder
 */
module.exports = class CustomTestEnvironment extends Environment {
    constructor({ globalConfig, projectConfig }, context) {
        super({ globalConfig, projectConfig }, context);
        if (typeof this.global.TextEncoder === 'undefined') {
            const { TextEncoder } = require('util');
            this.global.TextEncoder = TextEncoder;
        }
    }
};
cetgtptt

cetgtptt6#

下巴别塔工厂

● Test suite failed to run

    ReferenceError: TextEncoder is not defined

      1 | import assert from 'assert'
    > 2 | import { fromUrl, parseDomain, ParseResultType } from 'parse-domain'
        | ^
      3 | import { toUnicode } from 'punycode'
// ...
setupFiles: [`<rootDir>/jest-shim.js`],
testEnvironment: 'jest-environment-jsdom',
// ...
import { TextDecoder, TextEncoder } from 'util'

global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder
snvhrwxg

snvhrwxg7#

使用以下配置时不工作

"testEnvironment": "<rootDir>/tests/custom-test-env.js"

const NodeEnvironment = require('jest-environment-node');

// A custom environment to set the TextEncoder that is required by mongodb.
module.exports = class CustomTestEnvironment extends NodeEnvironment {
  async setup() {
    await super.setup();
    if (typeof this.global.TextEncoder === 'undefined') {
      const { TextEncoder } = require('util');
      this.global.TextEncoder = TextEncoder;
    }
  }
}

使用“笑话”:“^28.0.3”,

kr98yfug

kr98yfug8#

虽然所有其他的答案似乎工作正常,但我不能在我的react-scripts应用程序中使用它们中的任何一个。
为了解决这个问题,我使用了this approach,它解决了我的问题。
这种方法不需要将测试环境添加为jest配置。

n8ghc7c1

n8ghc7c19#

将此添加到src/setupTests.ts

import '@testing-library/jest-dom';
import { TextEncoder } from 'util';

global.TextEncoder = TextEncoder;

相关问题