Skip to article content
FrontendXLesson 08 / 24

Accessible Queries and Real User Events

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.

intermediate · about 35 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Query elements by their accessible role and name.
  • Simulate realistic user interaction sequences.
  • Use tests to surface accessibility defects.

Overview

#

The accessible name is the contract

Every interactive element has an accessible role and an accessible name. A button's role is button and its name is its text or its aria-label. A text input's role is textbox and its name comes from a <label>. Querying by role and name tests the same thing a screen reader uses, so a passing test is also evidence that the element is reachable.

snippet.js
// conceptual queries
// getByRole('button', { name: 'Save' })
// getByRole('textbox', { name: 'Email' })
// getByRole('checkbox', { name: 'Remember me' })

A missing label is a test failure

If a test cannot find a textbox by its label, a screen-reader user cannot find it either. That is not a test problem; it is a real accessibility defect. Writing tests through accessible queries turns the test suite into an accessibility check for free.

user-event over raw dispatch

Dispatching a bare click event is fine for a button, but real interaction is richer. Typing into an input fires focus, keydown, input and change. A user-event library models these sequences, including focus management and disabled-state behavior. Testing with user-event catches defects that a single synthetic event misses, such as a handler that only listens for change but not input.

Focus and keyboard

Keyboard users navigate with Tab, Enter and Space. Test that a control is reachable by keyboard and that Enter activates it. Test that focus moves to a dialog when it opens and returns to the trigger when it closes. These are behaviors, and behaviors deserve tests.

Do not assert on aria attributes as decoration

Asserting the aria-expanded attribute is meaningful only if the component actually behaves accordingly. Assert on the outcome the attribute promises: the menu content is now visible and reachable. The attribute is a signal, not the goal.

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.

  1. Exercise 1Predict

    A button has `aria-label="Close dialog"` and no visible text. What name does a role query use?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    const button = document.createElement('button');
    button.setAttribute('aria-label', 'Close dialog');
    console.log(button.getAttribute('aria-label'));
    Choose the best answer
  2. Exercise 2Explain

    Explain how querying by role and name turns a test suite into an accessibility check.

    Reveal the reference answer
    reference.javascript
    A role query only succeeds when the element exposes the expected role and an accessible name. If a textbox has no associated label, its accessible name is empty and the query fails. That failure is the same defect a screen-reader user experiences. So a suite that queries through roles and names fails whenever an element becomes unreachable, which keeps accessibility regressions visible.

    The answer should connect query success to the accessibility tree and treat a failed query as a real defect, not a test inconvenience.

  3. Exercise 3Implement

    Implement `labelInput(id, text)` that creates a `<label>` associated with the input id and returns it. `const label = labelInput('email', 'Email'); console.log(label.getAttribute('for'), label.textContent)` should print `email Email`.

    starter.javascript
    function labelInput(id, text) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function labelInput(id, text) {
      const label = document.createElement('label');
      label.setAttribute('for', id);
      label.textContent = text;
      return label;
    }

    Authored expected output: email Email

    The for attribute links the label to the input id, which gives the input its accessible name. Without this association, a role query for the textbox by name would fail.

  4. Exercise 4Debug

    This input has no accessible name, so a screen reader announces only 'edit text'. Add the missing association.

    starter.javascript
    const input = document.createElement('input');
    input.id = 'email';
    const label = document.createElement('div');
    label.textContent = 'Email';
    document.body.append(label, input);
    console.log(label.getAttribute('for'), label.textContent);

    Reveal the reference answer
    reference.javascript
    const input = document.createElement('input');
    input.id = 'email';
    const label = document.createElement('label');
    label.setAttribute('for', 'email');
    label.textContent = 'Email';
    document.body.append(label, input);
    console.log(label.getAttribute('for'), label.textContent);

    Authored expected output: email Email

    A div with text is not associated with the input, so it provides no accessible name and has no for attribute. Changing the element to a label with a matching for attribute links the two and gives the input a real name.

  5. Exercise 5Test

    Write a test that proves a search box is reachable by its label and that typing updates its value.

    starter.javascript
    function createSearch() {
      const label = document.createElement('label');
      label.setAttribute('for', 'q');
      label.textContent = 'Search';
      const input = document.createElement('input');
      input.id = 'q';
      input.type = 'text';
      return { label, input };
    }

    Reveal the reference answer
    reference.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }
    const { label, input } = createSearch();
    assertEqual(label.getAttribute('for'), input.id, 'label points at input');
    assertEqual(label.textContent, 'Search', 'accessible name');
    input.value = 'widgets';
    input.dispatchEvent(new Event('input', { bubbles: true }));
    assertEqual(input.value, 'widgets', 'value updated');
    console.log('search box verified');

    Authored expected output: search box verified

    The first two assertions verify the accessible name association, which is what a role query depends on. The third simulates typing and confirms the value updates, covering the input path.

  6. Exercise 6Interview

    In an interview, explain how you would test a modal dialog for keyboard accessibility.

    Reveal the reference answer
    reference.javascript
    I open the dialog with a keyboard-reachable trigger and assert focus moves into the dialog. I press Tab and assert focus stays inside the dialog rather than escaping to the page behind it. I press Escape and assert the dialog closes and focus returns to the trigger. I also assert the dialog has an accessible name and role dialog. Each of these is a behavior, so each gets an assertion.

    The answer should name focus trap, Escape to close, focus return and the accessible role, all as testable behaviors.

Common misconceptions

#
  • Accessibility is a separate audit and not part of testing.
  • Dispatching a click event is equivalent to a real user click.
  • Test ids are the most reliable way to query elements.

Follow-up practice

#
  • testing-integration
  • testing-e2e-browser

Related resources

#

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.

© 2026 FrontendX. All rights reserved.