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

vit*_*y-t 5 javascript jsdom jestjs

我正在尝试用jsdomand做最简单的事情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);
    });
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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

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

花了很多时间后,我很困惑我找不到任何解决方案来完成这样一个基本任务:(

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

Pat*_*wis 2

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

/* eslint-env jest, es6, node */

// loads the necessary node packages
const jsdom = require( 'jsdom' );
const { JSDOM } = jsdom;
const fs = require( 'fs' );

// __dirname is a Node.js global object
// https://nodejs.org/api/globals.html
const html = fs.readFileSync( __dirname + '/app/donation-types.html' ).toString();

// HTML to be imported as DOM
// const html = './app/donation-types.html';
var dom = new JSDOM( html );

// set the global window and document objects using JSDOM
// global is a node.js global object
if ( global !== undefined ) {
  global.window = dom.window;
  global.document = dom.window.document;
}

// requires my code to be tested
require( './app/file.js' );

test( 'sees if window is available before loading DOM...', () => {
    expect( window !== undefined ).toBe( true );
} );

test( 'verifies document is available before loading DOM...', () => {
    expect( document !== undefined && document !== null ).toBe( true );
} );
Run Code Online (Sandbox Code Playgroud)