简体   繁体   中英

Appending a html file to JSDOM in mocha test file

是否可以将Jtdom附加一个HTML文件,而该Jsdom已经加载了单独的HTML文件?

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.

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM