vitaly-t
vitaly-t

Reputation: 25840

jsdom error: utf-8 is not recognized as encoding for HTML

I'm trying to do the simplest thing with jsdom and jest - loading up an HTML file to test its 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);
    });

And I get the following error:

Error: Encoding not recognized: 'UTF-8' (searched as: 'utf8')

And I found the same issue against the library here, which was closed without offering any solution.

After having spent many hours, I'm buffled that I cannot find any solution to such a basic task :(

Any idea how to overcome this issue?

Upvotes: 5

Views: 2669

Answers (3)

aarkerio
aarkerio

Reputation: 2354

On Jest, putting this on top of the file worked for me:

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

I don't know why. :-|

Upvotes: 0

Jona
Jona

Reputation: 1061

Adding to @Patrick Lewis' answer, you can add the following to start selecting elements:

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

Though I can't for the life of me understand why this isn't possible:

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

Upvotes: 0

Patrick Lewis
Patrick Lewis

Reputation: 83

A better way is to read the file as a string and then not use fromFile() at all:

/* 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 );
} );

Upvotes: 2

Related Questions