我有这两个文件:
test.js:
const jsdom = require("jsdom");
const hello = () => {
console.log("hello!");
};
module.exports = {
hello
};
和
server.js:
const hello = require('./stuff/test');
hello.hello();
目录结构:
myprojectfolder
backend
src
stuff
test.js
server.js
当我运行 server.js
时,我得到了 ReferenceError: TextEncoder is not defined
错误:
/home/myusername/projects/myprojectfolder/node_modules/whatwg-url/lib/encoding.js:2
const utf8Encoder = new TextEncoder();
^
ReferenceError: TextEncoder is not defined
如果我从 test.js
中删除 const jsdom = require("jsdom");
行,server.js
运行正常并且没有任何错误(输出 hello
)。
为什么会发生这种情况以及如何修复它(同时仍然能够在 test.js
中导入和使用 jsdom
?)。
最佳答案
好吧,我花了一整天的时间,但最终我设法把它拉到一起。 我的问题是由于该错误,测试没有运行。
因此,在“脚本”下的 package.json 中,我添加了以下内容:
"test": "jest --verbose --runInBand --detectOpenHandles --forceExit"
在 jest.config.js 中,我添加了以下内容:
globals: {
"ts-jest": {
tsConfigFile: "tsconfig.json"
},
TextEncoder: require("util").TextEncoder,
TextDecoder: require("util").TextDecoder
}
关于javascript - 引用错误 : TextEncoder is not defined when importing jsdom library,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71163892/