【发布时间】:2020-10-06 10:03:00
【问题描述】:
我有一些代码使用 DOM Parser 将 HTML 字符串转换为 Document。然后根据类名遍历 DOM 找到一个元素。
helper.js
export function stringToHTML(htmlString) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
return doc.body;
}
export function getTextBoxInfo(htmlContent) {
const textBox = {
element: null,
index: null
};
htmlContent.getElementsByClassName('document-content')[0].children.forEach((ele, index) => {
if (ele.getAttribute('class').includes('freetext')) {
textBox.element = freeTextElement;
textBox.index = index;
}
});
return textBox;
}
helper.test.js
describe('The getTextBoxInfo function', () => {
it('returns an object with text box element and its position', () => {
const htmlString = `<div class="document-content">
<div class="content" id="bfb53c88"> Heading </div>
<div class="freetext" contenteditable="true"> Content </div>
</div>`;
const htmlContent = helper.stringToHTML(htmlString);
const textBox = helper.getTextBoxInfo(htmlContent);
expect(true).toBe(true);
});
});
它适用于源代码。 DOM Parser 转换的文档是,
但在单元测试(JEST)期间输出不同,
因此规范失败并出现以下错误,
TypeError: 无法读取未定义的属性 'children'
在线 - htmlContent.getElementsByClassName('document-content')[0].children
我无法编写测试。
【问题讨论】:
-
您正在调用
helper.stringToHTML(htmlString),然后在该结果上调用helpers.stringToHTML(...)。好像搞错了? -
这实际上是一个错字,只是在尝试不同的东西。更新后问题依然存在。
-
那么,
DOMParser在测试中的结果没有.getElementByClassName?那是对的吗?你得到什么样的错误,在哪一行? -
@DimaParzhitsky 下面是错误,TypeError: Cannot read property 'children' of undefined at the line - htmlContent.getElementsByClassName('document-content')[0].children
-
谢谢!您能否在原始问题中也添加此信息?
标签: javascript html dom jestjs domparser