简体   繁体   中英

Testing against a DOM in Jest and plain JavaScript

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.

  1. Does Jest support defining a DOM to test with?
  2. How would I handle updates to the DOM (eg testing that the DOM changed after a click event)

Thanks!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM