JavaScript · Advanced level

Advanced level · Module 1: Testing JavaScript · Lesson 3 of 4

Testing DOM Code

Test code that renders and responds to events using a simulated DOM, focusing on what users see and do.

In this lesson you will

  • Test rendering and events with a simulated DOM
  • Write tests from the user's point of view

Key concepts

jsdomrendering testssimulated eventsqueries by role and text

The lesson

DOM code can be tested in Node.js with jsdom, a JavaScript implementation of the browser DOM. Create a document, run your render function and check the resulting elements.

Test what users experience: the text shown, the buttons available and what happens when they click. Find elements by their text or accessible role rather than by CSS classes that may change.

Simulate events with element.dispatchEvent(new Event("click", { bubbles: true })) or by calling form.requestSubmit(), then assert the new state of the page.

Step by step

  1. Set up jsdom in a test.
  2. Render the entry list and check the items.
  3. Simulate deleting an entry and check the result.
  4. Submit an invalid form and check the error message.

Practice activity

Write DOM tests for the budget app's list and form behaviour.

Expected result: Tests cover rendering, deletion and validation messages, and fail when the rendering code is broken.

Check your understanding

  1. What is jsdom?

    Show answer

    A JavaScript implementation of the browser DOM for use in Node.js.

  2. Why find elements by text or role rather than CSS class?

    Show answer

    Tests then reflect what users see and break less when styling changes.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.