Home > Software engineering >  How to build an HTML DOM from a multiline string and access child elements in Jest?
How to build an HTML DOM from a multiline string and access child elements in Jest?

Time:01-02

Problem:

I'm trying to build an HTML DOM from a multiline string in Jest in order to test a browser extension.

However, when I try to access the child elements of the DOM, they are being returned as strings instead of DOM nodes.

What I've tried:

I have tried multiple approaches, but they all seem to have the same issue.

const html = `
<div id="id1">
<p id="id2">
<span id="id3">Hello World</span>
</p>
</div>
`

const template = document.createElement('template')
template.innerHTML = html.trim()
console.log(template.content.firstChild?.firstChild) // Text {Symbol(impl): TextImpl}

const htmlParser = new DOMParser()
const parsed = htmlParser.parseFromString(html.trim(), 'text/html')
console.log(parsed.body.firstChild?.firstChild) // Text {Symbol(impl): TextImpl}

const dom = new JSDOM(html.trim())
console.log(dom.window.document.body.firstChild?.firstChild) // Text {Symbol(impl): TextImpl}

(And of course the testEnvironment: "jsdom" in jest.config.js)

Question:

Is there a way to correctly build an HTML DOM from a multiline string and access its child elements in Jest?

CodePudding user response:

Already answered here and here:

The browser insert a text node when there are white spaces or new lines in your code. You are targeting one of those.

To skip those text nodes, you can use template.content.firstElementChild?.firstElementChild to skip the text nodes.


You can try without any whitespaces like:

const html = `<div id="id1"><p id="id2"><span id="id3">Hello World</span></p></div>

Or by doing a regex/replace function to remove all useless whitespaces, but for me the best solution will to use "querySelector"

  • Related