praveen
praveen

Reputation: 43

Appending a html file to JSDOM in mocha test file

Is that possible to append a html file to Jsdom which already been loaded with a seperate html file?

Upvotes: 0

Views: 1620

Answers (3)

CSBatchelor
CSBatchelor

Reputation: 174

The other answers replace the body's inner html. The OP wants to append:

Dependencies:

npm install jsdom

Solution:

const {JSDOM} = require("jsdom");
const fs      = require("fs");

const appendJSDOM = (dom, htmlFile) => {
    const html = fs.readFileSync(htmlFile).toString();
    dom.window.document.body.insertAdjacentHTML('beforeend', html);
}

JSDOM.fromFile("file1.html")
.then(dom => {
    appendJSDOM(dom ,"file2.html");
    console.log(dom.serialize());
});

You can keep calling appendJSDOM() to append more html files. But like the other answers have said you should omit the <html>, <head>, and <body> tags in the additional html files.

insertAdjacentHTML can also insert HTML in different places depending on what you put as the first argument.

Upvotes: 2

user515
user515

Reputation: 45

I think this one will help.

require('jsdom-global')();
var fs = require('fs');
document = window.document;
var dashboard = 
fs.readFileSync('yourHtmlFile').toString();
document.documentElement.innerHTML  = dashboard;

Upvotes: 1

Elliot B.
Elliot B.

Reputation: 17661

Yes, you can do that. The simplest approach would be to:

  1. Create your initial DOM with jsdom.
  2. Read in the second HTML file to a string using fs.
  3. Append the contents of the second HTML file to the original DOM returned by jsdom.

Install

npm install jsdom --save-dev
npm install fs --save-dev

Example code:

var jsdom = require('jsdom').JSDOM;
var fs = require('fs');
var document = (new jsdom('<!DOCTYPE html><html><head></head><body></body></html>')).window.document;
var secondHtml = fs.readFileSync('HelloWorld.html').toString();
document.body.innerHTML = secondHtml;

Note that your second HTML should exclude <html>, <head> and <body> tags. Otherwise you'll have problems with a <body> tag inserted inside an existing <body> tag.

Upvotes: 1

Related Questions