Reputation: 11890
Say I have component that's rendered and then mounted on to a DOM node when render()
is called:
render() {
// Render the HTML elements
const content = renderParent();
// Mount onto the DOM element with id `app`;
let element = document.getElementById('app');
element.innerHTML = '';
element.appendChild(div);
}
renderParent() {
const div = document.createElement('div');
div.classList.add('foo', 'bar');
div.innerHTML = renderChild();
return div
}
renderChild() {
const span = document.createElement('span');
span.innerText = 'ayyy lmao';
return span;
}
export { render }
(The above is oversimplified. In reality, there's layers of nested child components spread across several files and the elements are more complex)
I'm new to using Jest and JavaScript and I wanted to use Jest to write some tests.
I can easily test the behavior of renderParent()
and renderChild()
because they return HTMLElement objects, and I can make assertions on various properties.
But how do I test the behavior of the top-level render()
method? This doesn't return anything, but instead renders its contents into the DOM.
Thanks!
Upvotes: 1
Views: 2147
Reputation: 118
Does Jest support defining a DOM to test with?
Yes, it does! Actually, Jest comes bundled with a DOM implementation already, called jsdom.
How would I handle updates to the DOM
Although not all DOM APIs are implemented in jsdom, given your use case you should be able to just inspect the DOM tree the same way you would in a browser console.
So with Jest's out-of-the-box offering, you could create your DOM elements, assert their state, run your update, and then reassert that DOM state has changed.
Upvotes: 1