【问题标题】:jsdom error: utf-8 is not recognized as encoding for HTMLjsdom 错误:utf-8 未被识别为 HTML 编码
【发布时间】:2020-11-27 01:10:40
【问题描述】:

我正在尝试用jsdomjest 做最简单的事情——加载一个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')

我在here 库中发现了同样的问题,该库已关闭且未提供任何解决方案。

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

知道如何解决这个问题吗?

【问题讨论】:

    标签: jestjs jsdom


    【解决方案1】:

    更好的方法是将文件作为字符串读取,然后根本不使用 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 );
    } );
    

    【讨论】:

      【解决方案2】:

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

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

      虽然我一生都无法理解为什么这是不可能的:

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

      【讨论】:

        【解决方案3】:

        在 Jest 中,将其放在文件顶部对我有用:

         require('iconv-lite').encodingExists('foo'); // utf-8 support
        

        我不知道为什么。 :-|

        【讨论】:

          猜你喜欢
          • 2012-09-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多