Volume 2 Companion: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Companion: The Web Frontend

V2·26

Frontend Testing

Companion to Volume 2, chapter 26: how test strategy, techniques and specialised testing connect; new angles (test levels as a kitchen's tasting, inspection and dinner service; a mock as a stand-in actor; mutation testing as a fire drill for the tests themselves); what the chapter simplifies, measured: jsdom, where a button is 0 × 0, every rule inside @layer is ignored and var() is never resolved; axe, which reported the same on an error page before and after the fix for focus left on the page and a field not marked invalid; and random tests, where 20,000 generated event sequences killed 4 of 15 mutants of a state machine; the theory behind it; how pixelmatch decides that two pixels differ and that a difference is only anti-aliasing; four debugging drills, including a visual test that failed only in the full suite and a React card that rendered 71 pixels differently because one line became three text nodes; interview questions with how to approach each.

6 sections · ~14 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 26 has three strands. Strategy and levels: what to test and why, unit tests, component tests with Testing Library, end-to-end tests with Playwright, runners. Techniques: fixtures, mocking, network interception with MSW, traces and debugging. Specialised testing: visual regression, accessibility, performance, contract tests, and how frontend testing differs from backend testing.

strategy and levels techniques specialised testing what to test risk, behaviour, cost unit tests pure logic, fast component tests Testing Library, jsdom end-to-end Playwright, real browser runners Vitest, Jest, node:test fixtures data and environments mocking fakes, spies network interception MSW, routes traces, debugging why a test failed flakiness waits, isolation visual regression pixels, thresholds accessibility axe, AX tree, keyboard performance budgets, traces contract tests fakes stay honest vs backend testing what differs most at then fewest at run by with at the network debug with fight and and and see goes deeper: ch16 contracts · ch20 accessibility · ch27 performance · ch28 security · Volume 3 backend testing exercises: P1–P9 queries, mutants, mock drift, fake timers, visual thresholds, Playwright suite, perf tests, contract, test plan
Concept map of chapter 26, frontend testing: strategy and levels (what to test, unit, component and end-to-end tests, runners), techniques (fixtures, mocking and network interception, traces and debugging) and specialised testing (visual regression, accessibility, performance, contract tests, frontend versus backend testing), with links such as testing behaviour through what users see and fakes needing contracts to stay honest.

The links worth remembering:

  • Each level sees a different part of the truth. Unit tests see logic; component tests in jsdom see the DOM but not CSS or layout (Gaps 1); browser tests see what the user gets. Choose the level by where the bug you fear would show.
  • Every fake needs something keeping it honest. A mock, an MSW handler or a jsdom environment is a model of the real thing; contract tests, real-browser runs or recorded traffic are what tell you when the model has drifted.
  • Test the tests. Coverage says code ran; mutation testing and deliberate breakage say a test would notice if it were wrong (Gaps 3, drill D4).

Explain it differently

1. Test levels are tasting, inspection and dinner service. The cook tastes each sauce (unit tests: fast, many, narrow); the head chef inspects each plate before it goes out (component tests); and a full dinner service with real guests (end-to-end) is the only test of whether the whole evening works. You do the first constantly, the last rarely.

2. A mock is a stand-in actor. Useful in rehearsal, but if the stand-in says lines the real actor never would, rehearsal goes perfectly and opening night fails. Contract tests check the stand-in's script against the real actor's.

3. jsdom is a floor plan, not the building. It tells you which rooms exist and how they connect (the DOM), but not how big they are, what colour the walls are, or whether a door is blocked (Gaps 1).

4. Mutation testing is a fire drill for the tests. You set small, deliberate fires (change === to !==) and check that an alarm goes off. An alarm that stays silent tells you about the alarm, not the building (drill D4).

5. Property-based testing is an inspector with a random checklist. Instead of checking the three rooms you thought of, they check hundreds of rooms you didn't, and when they find a problem, they find the smallest room where it still happens (shrinking).

6. A flaky test is a smoke detector that goes off when someone makes toast. After a few false alarms, everyone ignores it, including the time there's a fire. Fixing flakiness is about keeping the signal trusted.

7. Visual regression is a photo comparison at the pass. The plate must look like the reference photo; a strict comparison catches a sprig of coriander in the wrong place, and also the photographer moving slightly (Code walkthrough: telling real changes from noise).

8. Accessibility tests are a guest with a different way of eating. Automated checks confirm there's a fork on the table; only someone actually eating with it finds that it's too far away to reach (Gaps 2).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from jsdom 27.0.0, @testing-library/dom 10.4.1, axe-core 4.14.0, fast-check 4.10.2, Chromium and the build's stage 26 (exp/26), unless stated.

1. jsdom has no layout, and doesn't read modern CSS. The chapter says component tests run in jsdom, "a simulated browser", and recommends real browsers for layout. How far the simulation goes, asked of one page in jsdom and in Chromium, with the build's real stylesheet:

Terminal
button "Accept" width x height                 jsdom: 0 x 0                      Chromium: 156 x 46
card background colour                         jsdom: rgba(0, 0, 0, 0)           Chromium: rgb(255, 255, 255)
button hidden by a stylesheet, visible?        jsdom: checkVisibility missing    Chromium: false
pointer-events: none button's pointer-events   jsdom: none                       Chromium: none
getByRole button "Hidden by a stylesheet"      jsdom: not found                  Chromium: not found

No layout, as expected: every box is 0 × 0, so target sizes, overflow and "is it on screen" can't be tested. More surprising is the card's background. A smaller test explains it:

Terminal
.plain    colour in jsdom: rgb(1, 2, 3)
.layered  colour in jsdom: rgb(0, 0, 0)
.tokens   colour in jsdom: var(--c)

jsdom ignores rules inside @layer, and returns var(--c) unresolved instead of a colour. The build's stylesheet puts every rule in a cascade layer (stage 14) and every colour in a custom property, so in jsdom the build has, in effect, no stylesheet at all. Simple rules outside layers still work (the display: none button was correctly not found). Tests of behaviour and roles are fine in jsdom; anything about appearance, visibility from modern CSS, layout or focus rings needs a real browser, which is why the build's suite runs in Chromium.

2. Automated accessibility checks pass pages that keyboard and screen-reader users can't use. The chapter recommends axe, noting it finds "about a third" of issues. Stage 26's suite found two real problems on the order form's error page: focus stayed at the top of the page, so a keyboard or screen-reader user didn't land on the errors, and the invalid field wasn't marked invalid or linked to its message. axe on that page, before and after the fix:

Terminal
before (served): axe violations [] | focus on BODY
after  (served): axe violations [] | focus on DIV

(The two versions are the same server-rendered page with and without stage 26's three changes, served from the app's origin through request interception so the stylesheet loads; the field's aria-invalid was absent before and true after.) axe's result didn't change, because both problems are about behaviour and relationships between elements that no static rule can judge: where focus goes after a submission, and whether this error belongs to that field. They were found by tests written as a user's task (submit with an error, ask the accessibility tree what is focused, what the field's state and description are). Automated rules are the floor; task-based tests through the accessibility tree and keyboard are the next level, and a session with a real screen reader is the one after that.

3. Many random inputs don't make a strong test. The chapter presents property-based and generated tests as stronger than examples. The build's connection machine has had a test since stage 21 that runs 20,000 random event sequences and checks that every state reached is a designed one and the status line agrees. A mutation run (change one operator, rerun the tests) on the compiled module:

Terminal
web/kitchen/connection.js: 4 of 15 mutants killed

The random test checked that the machine stays in designed states, not which designed state each event leads to: swapping e.type === 'error' for !== still produced valid states, just the wrong ones. A table of every state and event with its exact next state killed 8 more:

Terminal
web/kitchen/connection.js: 12 of 15 mutants killed
total: 25 of 29 killed (86%)

The three left change c.since ?? now to c.since || now, which differs only when since is 0 (midnight on 1 January 1970). They're equivalent in practice. The opposite lesson came from fast-check in the same stage: a property comparing applySnapshot with a model found a real bug in two inputs (an order open before the snapshot and closed in it wasn't reported as gone). Random inputs are powerful when the property is strong; a weak property checked 20,000 times is still a weak test.

Common misconceptions

Misconception What's actually true Where it's shown
"jsdom is a lightweight browser." No layout, no @layer, no resolved custom properties. Gaps 1
"axe passing means the page is accessible." axe was identical before and after fixing focus and invalid state. Gaps 2; drill D2
"More generated cases make a stronger test." 20,000 sequences killed 4 of 15 mutants. Gaps 3; drill D4
"Visual tests are too flaky to be strict." Zero tolerance held across six runs once data and anti-aliasing were controlled. Drill D1; Code walkthrough
"Two components that look the same render the same." Three text nodes instead of one changed 71 pixels. Drill D3
"Unreachable inputs don't need tests." The snapshot bug needed an input the server never sends, until it does. Gaps 3

Theoretical gaps: the ideas behind the chapter

1. Tests are samples from an input space. Example tests pick points; property tests sample randomly; exhaustive tests cover small finite spaces (the transition table: 5 states × 5 events). Choosing which is choosing where bugs are likely to be: at boundaries, combinations, and states nobody listed.

2. Mutation testing measures a test's power, like a statistical test. A test suite is a detector; mutants are known positives; the kill rate estimates sensitivity. Equivalent mutants (no observable difference) are the irreducible noise, which is why 100% is rarely the goal.

3. The test oracle problem. Running code on many inputs is easy; knowing the right output for each is hard. Properties (invariants, round trips, comparison with a simpler model), metamorphic relations (if A then B), and differential testing (three views must render the same card) are ways to get an oracle without writing every answer by hand.

4. Flakiness is non-determinism you didn't control. Time, ordering, shared state, randomness and the environment are the sources; each test must either control them (fixtures, fake clocks, isolated servers) or tolerate them (waiting for conditions, not durations). Drill D1's failure was shared state (order ids) between tests.

5. The testing pyramid is an economic model. Many cheap, fast, narrow tests; fewer expensive, slow, broad ones. Measured costs make it concrete: the build's 31 unit tests run in 0.5 s, its 24 browser tests in 11–12 s.

6. Accessibility testing is testing an interface for another kind of client. The accessibility tree is an API the page offers to assistive technology; testing it through that API (roles, names, states, focus) is contract testing for a second consumer.

Applying it

Code walkthrough

The build's visual test compares screenshots exactly, ignoring per-channel differences up to 2. Most visual testing tools use pixelmatch instead (Playwright's toHaveScreenshot among them). It decides two things per pixel: is the colour difference noticeable, and is it just anti-aliasing? Excerpts from pixelmatch 7.1.0, index.js, installed from npm.

A perceptual colour difference

JavaScript
function colorDelta(img1, img2, k, m, yOnly) {
    // … read r, g, b, a of both pixels; blend with a background if transparent …
    const y = dr * 0.29889531 + dg * 0.58662247 + db * 0.11448223;

    if (yOnly) return y; // brightness difference only

    const i = dr * 0.59597799 - dg * 0.27417610 - db * 0.32180189;
    const q = dr * 0.21147017 - dg * 0.52261711 + db * 0.31114694;

    const delta = 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;

    // encode whether the pixel lightens or darkens in the sign
    return y > 0 ? -delta : delta;
}

Instead of comparing red, green and blue separately, it converts the difference to YIQ (brightness and two colour axes, from analogue colour television) and weights brightness most, because eyes are most sensitive to it. The main loop counts a pixel only if |delta| > 35215 * threshold², where 35215 is the largest possible delta: threshold 0.1 ignores differences below about 1% of the maximum.

Is it anti-aliasing?

JavaScript
function antialiased(img, x1, y1, width, height, a32, b32) {
    // … the 3×3 neighbourhood around (x1, y1) …
    for (let x = x0; x <= x2; x++) {
        for (let y = y0; y <= y2; y++) {
            if (x === x1 && y === y1) continue;

            // brightness delta between the center pixel and adjacent one
            const delta = colorDelta(img, img, pos * 4, (y * width + x) * 4, true);

            // count the number of equal, darker and brighter adjacent pixels
            if (delta === 0) {
                zeroes++;
                // if found more than 2 equal siblings, it's definitely not anti-aliasing
                if (zeroes > 2) return false;
            // … remember the darkest and the brightest neighbour …
        }
    }

    // if there are no both darker and brighter pixels among siblings, it's not anti-aliasing
    if (min === 0 || max === 0) return false;

    // if either the darkest or the brightest pixel has 3+ equal siblings in both images
    // (definitely not anti-aliased), this pixel is anti-aliased
    return (hasManySiblings(a32, minX, minY, width, height) && hasManySiblings(b32, minX, minY, width, height)) ||
           (hasManySiblings(a32, maxX, maxY, width, height) && hasManySiblings(b32, maxX, maxY, width, height));
}

An anti-aliased pixel sits on an edge: it's between a darker and a brighter neighbour, and those neighbours belong to solid areas (they have several identical neighbours themselves). A pixel with more than two identical neighbours is inside a flat area, so a change there is real. Differences judged to be anti-aliasing are drawn yellow in the diff image and not counted, unless includeAA is set.

Read it yourself

  1. Before running it: compare the build's light-theme card baseline with three images: the card with its corner radius changed from 8 px to 6 px, the React card from before the drill D3 fix, and the Angular card (which differed from the plain view's by 1 in one channel on 22 pixels). How many differing pixels does pixelmatch report at its default threshold of 0.1, and with includeAA: true?
  2. Which of the three changes would a default pixelmatch setting let through, and is that what you'd want?

Debugging drills

D1. The visual test passes alone and fails in the full suite

The card's visual test passes when run on its own. In the full suite it fails, every time, by about 300 pixels against the baseline. Masking the order id in the screenshot doesn't fix it.

D2. axe passes, and keyboard users are lost after a mistake

A customer types 25 for a dish (the limit is 20) and submits. The page reloads with an error box at the top. axe reports no violations. A keyboard user reports that after submitting they "don't know what happened", and a screen-reader user says the field doesn't say anything is wrong.

D3. The React card renders 71 pixels differently

The suite compares the card from the three views against each other. Plain and Angular match; React differs by 71 pixels, all in the dish line and the heading's edges, though the two look identical at normal size.

D4. Twenty thousand random tests, and a broken state machine passes

Someone changes if (e.type === 'error') to if (e.type !== 'error') in the connection machine. All tests pass, including the one that runs 20,000 random event sequences.

Career-oriented

Interview prep

Mid level

Q1. When would you test a component in jsdom, and when in a real browser?

How to get there. List what each environment implements, then what your component's correctness depends on.

Q2. A test fails one run in twenty. What do you do?

How to get there. Find the uncontrolled input before touching the test.

Senior level

Q3. Design a test strategy for a UI that exists in three implementations (plain, React, Angular) on one shared core.

How to get there. Decide what's tested once and what's tested per implementation.

Q4. How do you know your tests are good enough?

How to get there. Coverage is one signal; think about others that measure whether tests would catch bugs.

Staff level

Q5. Set accessibility testing standards for an organisation.

How to get there. Combine what automation can and can't catch with where humans are needed.

Q6. The frontend test suite takes 40 minutes and fails randomly. You have one quarter. What's the study plan?

How to get there. Measure first, then cut, then rebuild trust.