我在我的应用程序中使用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)
我想摆脱那个错误。我尝试使用“文本编码”包,但不确定在导入之前如何正确定义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
。
答案 0 :(得分:7)
jsdom
似乎没有为DOM全局定义TextEncoder
。因此,您可以将它与node.js一起填写。
test / custom-test-env.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 TextEncoder === 'undefined') {
const { TextEncoder } = require('util');
this.global.TextEncoder = TextEncoder;
}
}
}
npx react-scripts test --env=./test/custom-test-env.js