Ad

Append The HTML Tag To The Document. HierarchyRequestError: The Operation Would Yield An Incorrect Node Tree

I was testing my React/TypeScript project with Jest + Enzyme.

When I created an HTML tag and appended it to the document, I got an error. This was the unit test code that produced the error:

const htmlTag: HTMLElement = document.createElement('html');
htmlTag.setAttribute('myAttribute', 'myValue');
document.appendChild(htmlTag); // HierarchyRequestError: The operation would yield an incorrect node tree

So Jest didn't like something about adding an HTML tag to the document. A similar post implies that what I am trying to do is not possible, but since I need to test what my code does to a particular HTML attribute, how else would I test that?


Is there a better way to add the HTML tag to the document so that I can test its attributes later?

Ad

Answer

Is there a better way to add the HTML tag to the document so that I can test its attributes later?


The HTML tag didn't need to be added. I just "got" it!

const htmlTag = document.getElementsByTagName('html')[0]; // The html tag is still attached to the DOM

Now I can set or test its attributes per this code.

Ad
source: stackoverflow.com
Ad