[英]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:
最简单的方法是:
jsdom
. jsdom
创建您的初始DOM。 fs
. fs
将第二个HTML文件读入字符串。 jsdom
. jsdom
返回的原始DOM中。 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. 请注意,您的第二个HTML应该排除
<html>
, <head>
和<body>
标记。 Otherwise you'll have problems with a <body>
tag inserted inside an existing <body>
tag. 否则,您将在现有的
<body>
标记内插入<body>
标记时遇到问题。
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. 其他答案将替换正文的内部html。 The OP wants to append :
OP希望追加 :
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. 您可以继续调用
appendJSDOM()
来追加更多的html文件。 But like the other answers have said you should omit the <html>
, <head>
, and <body>
tags in the additional html files. 但是,就像其他答案所说的那样,您应该在其他html文件中省略
<html>
, <head>
和<body>
标记。
insertAdjacentHTML can also insert HTML in different places depending on what you put as the first argument. insertAdjacentHTML还可以将HTML插入不同的位置,具体取决于您放置的第一个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.