Search⌘ K

HTML-Based Tests

Explore how to use Jest and the jsdom library to write effective tests for HTML content and DOM events without a full browser. Learn to simulate user interactions, verify DOM updates, and handle event triggers like clicks using test-driven development approaches.

Jest uses a library named jsdom to allow for testing HTML elements and interactions. The jsdom is not an actual browser; it is a library that implements the JavaScript DOMThe Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web. API, and can, therefore, simulate a full-blown browser experience. The benefit of using jsdom is in the speed at which we can run our tests and the fact that we do not have to provide an environment that can run a full browser.

Running a full internet browser generally assumes that the tests are running on a standard computer and, as such, have an actual screen. This means that virtual machines that run tests must be configured with a screen, which adds the extra requirement of having a screen driver that can run at the required resolution.

Checking DOM updates

With jsdom and jquery installed, we can write a test that checks whether the DOM has been updated. Consider the following code:

TypeScript 4.9.5
function setTestDiv(text: string) {
$("#test_div").html(`<p>${text}</p>`);
}

Here, we have a function named setTestDiv, which has a single parameter named text of type string. This function is using jQuery to set the HTML of the DOM element with the id test_div. ...