Jestjs jsdom错误:utf-8未被识别为HTML编码

Jestjs jsdom错误:utf-8未被识别为HTML编码,jestjs,jsdom,Jestjs,Jsdom,我正在尝试用jsdom和jest做最简单的事情——加载一个HTML文件来测试它的DOM: const jsdom = require('jsdom'); const {JSDOM} = jsdom; JSDOM.fromFile('../src/index.html'), {}) .then(dom => { console.log(dom.serialize()); // need to run tests here... })

我正在尝试用
jsdom
jest
做最简单的事情——加载一个HTML文件来测试它的DOM:

const jsdom = require('jsdom');
const {JSDOM} = jsdom;

JSDOM.fromFile('../src/index.html'), {})
    .then(dom => {
        console.log(dom.serialize());

        // need to run tests here...
    })
    .catch(error => {
        console.log(error);
    });
我得到以下错误:

错误:无法识别编码:“UTF-8”(搜索为:“utf8”)

我在图书馆发现了同样的问题,图书馆关闭后没有提供任何解决方案

在花了许多小时之后,我被这样一个基本任务的解决方案弄糊涂了:(


您知道如何克服这个问题吗?

更好的方法是将文件作为字符串读取,然后根本不使用fromFile()

/*eslint环境笑话,es6,节点*/
//加载必要的节点包
const jsdom=require('jsdom');
const{JSDOM}=JSDOM;
常数fs=要求('fs');
//\uu dirname是一个Node.js全局对象
// https://nodejs.org/api/globals.html
const html=fs.readFileSync(_dirname+'/app/generation types.html').toString();
//要作为DOM导入的HTML
//const html='./app/generation types.html';
var dom=新的JSDOM(html);
//使用JSDOM设置全局窗口和文档对象
//global是node.js全局对象
如果(全局!==未定义){
global.window=dom.window;
global.document=dom.window.document;
}
//需要测试我的代码
需要('./app/file.js');
测试('在加载DOM之前查看窗口是否可用…',()=>{
expect(window!==未定义).toBe(true);
} );
测试('在加载DOM之前验证文档是否可用…',()=>{
expect(document!==undefined&&document!==null).toBe(true);
} );

添加到@Patrick Lewis的答案中,您可以添加以下内容以开始选择元素:

const doc = dom.window.document
const box = doc.querySelector("#blue-box")
虽然我一辈子都不明白为什么这是不可能的:

const $ = doc.window.document.querySelector
const box = $("#blue-box")

开玩笑的是,把这个放在文件的顶端对我来说很有用:

 require('iconv-lite').encodingExists('foo'); // utf-8 support
我不知道为什么-|