Component Testing with the DOM
Build a working model of automated testing from assertions to unit, component, API, integration, contract and end-to-end tests, then apply it to a single progressive task-board capstone where each milestone adds a real defect, a failing test, a corrected implementation and an expected result.
What you will be able to do
#- Render a component into a DOM container and query its output.
- Assert on what the user can see rather than internal state.
- Clean up rendered DOM between tests.
Overview
#A component test renders and observes
A component test mounts a component into a DOM container, drives it, and asserts on the rendered result. It is closer to the user than a unit test because it exercises the render logic and event wiring, but it does not need a browser or a server.
Query the way a user perceives
Query by text, label, role or placeholder, not by CSS class or internal test id. A query by visible text survives a refactor of class names and proves the user can actually see the content. A query by .btn-primary breaks when styling changes and proves nothing about accessibility.
// conceptual: render a button, then find it by its accessible name
// const button = screen.getByRole('button', { name: 'Save' });
Assert on output, not internals
Do not reach into component state or props. Assert on the DOM the user sees: the text content, the disabled attribute, the number of list items, the value of an input. If you must assert on state, the component is probably doing too much, or you are testing the wrong layer.
Clean up
Each test should start with an empty DOM. Mounting into a fresh container and removing it after the test prevents leakage between tests. A leaked node from a previous test can make a query ambiguous, so getByText throws because it found two matches.
Simulate events, do not call handlers
Calling a component's handler directly bypasses the wiring you want to test. Dispatch a real event on the DOM node instead, so the test covers the listener registration and the handler together. The next lesson covers the user-event library, which models realistic interaction sequences.
Keep component tests focused
A component test should answer one question: given these props and this interaction, does the rendered output match? If a test needs a real API, a router and a store, it has grown into an integration test and should be labeled and structured as one.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
Given a list component that renders one `<li>` per item, how many `<li>` elements exist after rendering with three items?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptfunction renderList(items) { const ul = document.createElement('ul'); for (const item of items) { const li = document.createElement('li'); li.textContent = item; ul.appendChild(li); } return ul; } const ul = renderList(['a', 'b', 'c']); console.log(ul.querySelectorAll('li').length);Exercise 2Explain
Explain why querying by visible text is more robust than querying by CSS class.
Reveal the reference answer
reference.javascriptVisible text is part of the user-facing contract. If the text changes, the user experience changed and the test should notice. A CSS class is an implementation detail used for styling; it can change during a redesign without any behavior change, so a class query breaks for no product reason. Text queries also fail when content is missing, which is a real accessibility and correctness signal.The answer should tie query choice to the user-facing contract and to false failures from implementation changes.
Exercise 3Implement
Implement `renderButton(label, disabled)` that returns a `<button>` element with the given text and disabled state. `const b = renderButton('Save', true); console.log(b.textContent, b.disabled)` should print `Save true`.
starter.javascriptfunction renderButton(label, disabled) { // your code here }Reveal the reference answer
reference.javascriptfunction renderButton(label, disabled) { const button = document.createElement('button'); button.textContent = label; button.disabled = disabled; return button; }Authored expected output: Save true
The function creates a real button element, sets its text content and its disabled property, and returns it. Both properties are directly observable and testable without touching any internal state.
Exercise 4Debug
This component test leaks DOM between tests, so a later `getByText('Save')` finds two buttons. Fix the test to clean up.
starter.javascriptfunction render() { const container = document.createElement('div'); container.innerHTML = '<button>Save</button>'; document.body.appendChild(container); } render(); render(); console.log(document.querySelectorAll('button').length);Reveal the reference answer
reference.javascriptfunction render() { const container = document.createElement('div'); container.innerHTML = '<button>Save</button>'; return container; } const first = render(); const second = render(); console.log(first.querySelectorAll('button').length, second.querySelectorAll('button').length);Authored expected output: 1 1
The original appends a fresh container to the shared document body on every render, so repeated renders accumulate buttons and a later query finds more than one. Returning a fresh container per render instead of appending it isolates each result and removes the cross-test leakage.
Exercise 5Test
Write a test that renders a counter component and proves the displayed count increments after a click event.
starter.javascriptfunction createCounter() { const button = document.createElement('button'); let count = 0; button.textContent = 'Count: 0'; button.addEventListener('click', () => { count += 1; button.textContent = 'Count: ' + count; }); return button; }Reveal the reference answer
reference.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); } const button = createCounter(); assertEqual(button.textContent, 'Count: 0', 'initial'); button.dispatchEvent(new Event('click')); assertEqual(button.textContent, 'Count: 1', 'after one click'); button.dispatchEvent(new Event('click')); assertEqual(button.textContent, 'Count: 2', 'after two clicks'); console.log('counter verified');Authored expected output: counter verified
The test dispatches real click events instead of calling the handler, so it covers the listener registration and the state update together. It asserts on visible text, which is what a user sees.
Exercise 6Interview
In an interview, explain the difference between a component test and an integration test in a frontend codebase.
Reveal the reference answer
reference.javascriptA component test mounts one component or a small group and asserts on its rendered output, using stubs for external collaborators like the network or the router. An integration test composes several real units, such as a form, a store and a mocked API, and verifies they work together. Component tests are fast and pinpoint rendering defects; integration tests catch wiring defects between units. I keep both, with more component tests than integration tests.The answer should distinguish scope and the collaborators that are real versus doubled, and should place both on a strategy.
Common misconceptions
#- Querying by CSS class makes tests more precise.
- Component state should be asserted directly for accuracy.
- Every component test needs a real browser.
Follow-up practice
#- testing-accessible-queries-and-events
- testing-integration
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.