I am trying to write a UI test for a HTML component using Jasmine and jsdom.
In my component I am using createTextNode
to generate the content of the DOM element.
However when the test runs the document.createTextNode
is returning an empty object
let dom = new JSDOM("<!doctype html><html><body></body></html>");
global.window = dom.window;
global.document = dom.window.document;
global.navigator = global.window.navigator;
let div = document.createElement("div");
let content = document.createTextNode("hello");
console.log(content); // Text {}
div.appendChild(content);
console.log(div.innerText) // undefined
Your usage is fine, your issue is here:
console.log(div.innerText) // undefined
innerText
isn't implemented in JSDOM, so you're seeing undefined
as your result. You'll need to use textContent
or innerHTML
to check the text instead:
import { JSDOM } from 'jsdom';
let dom = new JSDOM('<!DOCTYPE html>'), doc = dom.window.document;
let text = doc.createTextNode('here is some text');
let div = doc.createElement('div');
div.appendChild(doc.createElement('span')); // just for example
div.appendChild(text);
div.appendChild(doc.createElement('span')); // just for example
console.log('innerText:', div.innerText); // not implemented in JSDOM
console.log('textContent:', div.textContent); // this'll work
console.log('innerHTML:', div.innerHTML); // as will this
doc.body.appendChild(div);
console.log('full document:');
console.log(dom.serialize());
This will output:
innerText: undefined
textContent: here is some text
innerHTML: <span></span>here is some text<span></span>
full document:
<!DOCTYPE html><html><head></head><body><div><span></span>here is some text<span></span></div></body></html>
(See https://github.com/jsdom/jsdom/issues/1245 and the various linked issues therein.)