Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 44 ยท Real-world Charts and Integration

Accessibility and Testing for D3 Charts

Make D3 charts accessible with titles, ARIA roles, keyboard focus, data tables and color-safe palettes, and test chart code with unit tests of scales and DOM checks.

A chart that only works for people who can see colors, use a mouse and read small text is not finished. Accessibility (a11y) is also good design for everyone: keyboard shortcuts, clear labels and strong contrast help on phones, in bright sunlight and in presentations. SVG is a good starting point, because it is real DOM: text is text and elements can carry roles and labels. This lesson covers practical steps, then moves to testing, because charts are code and need tests like any other.

Give the chart a name and a description

For a screen reader, an SVG chart is by default a pile of unlabelled shapes. Wrap it as a single image with a title and description:

JavaScript
svg.attr("role", "img")
   .attr("aria-labelledby", "chart-title chart-desc");
svg.append("title").attr("id", "chart-title").text("Monthly sales, 2025");
svg.append("desc").attr("id", "chart-desc")
   .text("Bar chart. Sales rose from 12 thousand in January to 41 thousand in April.");

State what the chart shows and what the main insight is. This text is the alternative for people who cannot see the picture. Putting it also as visible text near the chart (a caption) helps everyone.

Offer the data as a table

Charts approximate numbers; a table gives them exactly and is the most robust alternative for assistive technology. You already have the data, so generating a table is cheap. Put it in a <details> element, or visually hide it:

JavaScript
const table = d3.select("#chart-wrap").append("details");
table.append("summary").text("View data as a table");
const t = table.append("table");
t.append("tr").selectAll("th").data(["Month", "Sales"]).join("th").text(d => d);
t.selectAll("tr.row").data(data).join("tr").attr("class", "row")
  .selectAll("td").data(d => [d.month, d.value]).join("td").text(d => d);

Keyboard navigation

Mouse-only tooltips exclude keyboard users. Make marks focusable and show the same information on focus:

Keyboard-accessible bars

The pattern is called a roving tabindex: only one bar is in the tab order (tabindex="0"), the others are reachable with arrow keys (-1). The aria-live="polite" region announces the focused bar to screen readers without stealing focus, and the bars also show a visible focus outline. Never remove focus outlines without replacing them.

Color and contrast

  • Do not rely on color alone. Add direct labels, patterns, different line dashes or marker shapes. About 1 in 12 men have a color-vision deficiency.
  • Use palettes designed for it: d3.schemeTableau10, d3.schemeObservable10, or colorblind-friendly sequential ramps such as d3.interpolateViridis, interpolateCividis and interpolateBlues. Avoid red/green as the only pair.
  • Text needs a contrast ratio of at least 4.5:1 against its background (3:1 for large text); marks and chart lines should reach 3:1 against the background.
  • Use d3.color(c).darker(1) or .brighter() to derive accessible variants, and check them with a contrast checker.
  • Honor user preferences: matchMedia("(prefers-reduced-motion: reduce)").matches is true for people who asked for less motion, so set transition durations to 0. prefers-color-scheme lets you switch to a dark palette.
JavaScript
const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
const dur = reduceMotion ? 0 : 600;

Text size and touch targets

Keep tick labels at least 12 px. Make interactive targets at least 24 by 24 CSS pixels (44 on touch-first designs); a thin line is hard to tap, so add an invisible wider stroke or an overlay rectangle for hit testing.

Testing D3 code

Charts look like they are hard to test, but most of the logic is plain functions and a DOM:

  1. Unit test the data and scale logic. Extract prepareData(rows), makeScales(data, size) and formatting into pure functions; assert on their output.
  2. Render into a DOM and query it. Under Vitest or Jest with the jsdom environment, call your chart function on a detached container and check the elements: how many rects, their attributes, text content of ticks. jsdom does not do layout, so getBBox() and getBoundingClientRect() return zeros: pass sizes in explicitly instead of measuring.
  3. Test interactions by dispatching events: rect.dispatchEvent(new MouseEvent("mouseenter")), then assert the tooltip text.
  4. Visual regression with a real browser (Playwright screenshots) for the final look, kept few and stable. Use deterministic data and disable animations (transition duration 0).
  5. Test with assistive tools by hand: tab through the chart, run a screen reader once, and run an automated checker such as axe for the obvious issues.

A tiny example, shown as a test file (read-only; it needs a test runner):

JavaScript
import { describe, it, expect } from "vitest";
import * as d3 from "d3";
import { barChart } from "./barChart.js";

describe("barChart", () => {
  it("draws one rect per datum with a label", () => {
    document.body.innerHTML = '<div id="host"></div>';
    d3.select("#host").datum([{ label: "A", value: 3 }, { label: "B", value: 5 }]).call(barChart());
    const rects = document.querySelectorAll("#host rect");
    expect(rects).toHaveLength(2);
    expect(document.querySelector("svg title").textContent).toMatch(/bar chart/i);
  });
});

The next TryIt shows the same idea in the browser without a test runner: a tiny assertion helper running checks against a chart built in the page.

A mini test of a chart

The last test fails on purpose so you can see how a failure message reads. Fix the expected number to make all five pass.

flowchart LR
  D["Data"] --> P["prepareData: pure, unit tested"]
  P --> S["scales: pure, unit tested"]
  S --> R["render: DOM test with jsdom"]
  R --> V["screenshot test for look"]
  R --> A["keyboard and axe checks"]

Test each layer with the cheapest tool that can find its bugs.

Common mistakes

  • Hiding information in tooltips that appear only on mouse hover.
  • Relying on red versus green, or on a legend that is far from the data.
  • Removing the focus outline with outline: none and giving nothing in return.
  • Testing with real timers and animations: set durations to 0 or use fake timers.
  • Asserting on exact path strings: they are fragile. Assert on counts, text and attributes you care about.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a roving tabindex?

    It keeps the page's tab order short while still letting keyboard users reach every mark.
  2. 2. Which pair of elements gives an SVG chart an accessible name and description?

    title and desc inside the svg, linked by aria-labelledby on an element with role=img, describe the chart as a whole.
  3. 3. How should you respond to prefers-reduced-motion: reduce?

    Some users get dizzy or distracted by motion; honor the setting by turning transitions off or shortening them.
  4. 4. Why does jsdom make measuring text with getBBox unreliable in tests?

    jsdom does not compute layout. Pass sizes into your chart rather than measuring in tests.

Summary

  • Name charts with role="img", title and desc; offer the data as a table.
  • Make marks focusable with a roving tabindex and announce focus through a live region.
  • Do not depend on color alone; check contrast and honor motion preferences.
  • Test pure data/scale functions, DOM output and interactions; use screenshots sparingly.

Next: Project: An Interactive Sales Dashboard