Courses / Frontend System Design, with JavaScript Foundations / Chapter 9
Module 4 · Requirements and Fundamentals · Chapter 9 of 21
Non-functional Requirements
Builds on Promises, Async Code and the Browser Event Loop, TypeScript for Frontend Engineers, The DOM, Events and Observers and How the Browser Loads and Renders a Page. Next up: Frontend Fundamentals: Components, State, Data and Rendering.
Part 1 · Performance as a requirement
Requirements that can be tested
A non-functional requirement says how well a system must work, not what it does. For a frontend it covers how fast pages load and respond, who can use them, which browsers they run in, which languages they speak and how safely they can be changed.
Functional requirements list actions: search for a product, add it to the cart, pay. Non-functional requirements describe the quality of those actions, and they only help if they can be checked. "The page should be fast" cannot be checked. "At least 75% of mobile visits reach the largest content in 2.5 seconds or less" can.
Google's Core Web Vitals give three such checks. Largest Contentful Paint (LCP) is how long the biggest image or block of text in the first screen takes to appear. Interaction to Next Paint (INP) is how long the page takes to show a response after a click, tap or key press. Cumulative Layout Shift (CLS) is how much visible content jumps around while the page loads.
| Metric | Good | Poor | What it protects |
|---|---|---|---|
| LCP | 2.5 s or less | more than 4 s | the wait before the page looks useful |
| INP | 200 ms or less | more than 500 ms | the feeling that taps and clicks work |
| CLS | 0.1 or less | more than 0.25 | not tapping the wrong thing as content moves |
Good
From a target to a budget
A target such as "LCP in 2.5 seconds" cannot be built directly. A performance budget turns it into limits on things you control: bytes of JavaScript, bytes of images, number of requests, third-party scripts. The team then rejects a change that breaks a limit, the same way it rejects a change that breaks a test.
The scene works one budget out on paper. The link speed and round-trip time are assumptions for a slow mobile connection, not measurements of any real network. Change them for your own users and the answer changes with them.
Budget for the LCP path: ≈ 256 KB (compressed HTML, CSS, JS and hero image together)
Read it as steps
A 2.5 second target, minus set-up time, times link speed, gives the bytes that fit.
The result is a planning number, and it is small. Everything the first screen needs, compressed, has to fit in about 256 KB on that link. Split it by what each part costs. JavaScript is the expensive part, because the same number of bytes also has to be parsed and run, and a mid-range phone has less processing power than the machine you develop on.
| Part of the page | Budget (our choice) |
|---|---|
| HTML | 20 KB |
Measuring with web-vitals
Google maintains a small open-source library, web-vitals, that reports the three metrics from inside a page. Each on... function takes a callback and calls it with the metric's name, value and rating, where the rating is good, needs-improvement or poor. The option reportAllChanges asks for every update instead of one final value.
The test page below has a hero image that the server delays by 300 ms and a button whose click handler holds the main thread for 250 ms, a stand-in for slow work.
<script type="module"> import { onLCP, onCLS, onINP } from '/wv.js' window.vitals = {} const keep = (m) => { const { name, value, rating } = m window.vitals[name] = { value: +value.toFixed(3), rating } } for (const on of [onLCP, onCLS, onINP]) { on(keep, { reportAllChanges: true }) } document.querySelector('#add').addEventListener('click', () => { const end = performance.now() + 250 while (performance.now() < end) {} // stands in for slow work document.querySelector('#out').textContent = 'Added' }) </script>
n1.html: the page, with web-vitals loaded as a module.
A Playwright script serves the page, opens it in Chrome with the CPU slowed four times, clicks the button with a real mouse event and prints what the library reported.
const page = await browser.newPage() await throttle(page, 4) // 4x CPU slowdown await page.goto('http://127.0.0.1:55830/') await sleep(1500) await page.click('#add') // a real click await sleep(3000) // INP is reported when the page is idle const v = await page.evaluate(() => window.vitals) for (const [name, m] of Object.entries(v)) { console.log(name.padEnd(4), String(m.value).padStart(6), m.rating) } await browser.close() server.close()
n1.mjs: the driver, last lines.
LCP 348 good CLS 0 good INP 264 needs-improvement
Output (Chrome 157, lab, this machine, 4x CPU throttling)
This is lab data: one controlled load on one machine. Over ten reruns here the LCP ranged from about 340 ms to about 680 ms, so read the line above as one sample. The 250 ms handler pushes INP to 264 ms here, which is above the 200 ms target and so "needs improvement". INP was 264 ms in five of the ten reruns and 272 ms in the other five; repeat lab runs before trusting one. CLS is 0 because the image has width and height and nothing moves.
Part 2 · Accessibility as a requirement
What the standard asks for
Accessibility means that people with disabilities can use the product, and so can people in temporary situations such as bright sunlight or one free hand. The shared standard is the Web Content Accessibility Guidelines (WCAG) from the W3C. Version 2.2 became a W3C Recommendation in December 2024.
WCAG is a list of success criteria, each testable and each at level A, AA or AAA. Most teams target level AA. WCAG 2.2 also removed one older criterion, 4.1.1 Parsing, and added new ones such as 2.5.8, the minimum size of a touch target.
| Criterion | Level | What it asks | Typical failure |
|---|---|---|---|
| 1.1.1 Non-text content | A | images have a text alternative | an img with no alt |
| 1.4.3 Contrast (minimum) | AA | text contrast at least 4.5:1 (3:1 for large text) | light grey text on white |
| 1.4.11 Non-text contrast | AA | controls and icons at least 3:1 | a pale input border |
| 2.4.7 Focus visible | AA | keyboard focus can be seen | outline: none with no replacement |
| 2.5.8 Target size (minimum) | AA | targets at least 24 by 24 CSS pixels, with exceptions | tiny icon buttons set close together |
| 4.1.2 Name, role, value |
The accessibility tree
Assistive technology such as a screen reader does not read pixels. The browser builds a second tree from the DOM, the accessibility tree, where each object has a role (what it is), a name (what it is called) and states (such as checked or expanded). The screen reader reads that tree aloud, and keyboard behaviour follows from the role.
Native elements fill in all of this for free. A button has the button role, takes its name from its text, joins the Tab order and responds to Enter and Space. A div with a click handler has none of it. The next script asks Chrome for the tree of each and then presses Tab once.
// What the accessibility tree holds for a div and for a button. import { launch } from '../h.mjs' const browser = await launch() const page = await browser.newPage() await page.setContent(` <div id="a" onclick="0" style="padding:8px">Place order</div> <button id="b">Place order</button>`) for (const id of ['a', 'b']) { const tree = await page.locator('#' + id).ariaSnapshot() console.log(`#${id}:`, tree.trim()) } await page.keyboard.press('Tab') const first = await page.evaluate(() => document.activeElement.id) console.log('first Tab stop:', first) await browser.close()
n3.mjs: read each control's tree entry, then press Tab.
#a: - text: Place order
#b: - button "Place order"
first Tab stop: bOutput (Chrome 157)
Watch for what the tree knows about each version of the control
Read it as steps
Checking with axe-core
axe-core is an open-source engine that runs accessibility rules against a loaded page. The @axe-core/playwright package connects it to Playwright. The script loads a page with typical mistakes, then a corrected one, and lists the rules that failed.
const bad = `<!doctype html><title>Order</title> <p style="color:#999;background:#fff">Free delivery above 499</p> <img src="data:image/gif;base64,R0lGODlhAQABAAAAACw="> <input type="text" placeholder="Phone number"> <a href="/help"></a> <div onclick="go()" style="padding:8px">Place order</div>` const good = `<!doctype html><html lang="en"><title>Order</title> <main><h1>Your order</h1> <p style="color:#595959;background:#fff">Free delivery above 499</p> <img src="data:image/gif;base64,R0lGODlhAQABAAAAACw=" alt=""> <label>Phone number <input type="text"></label> <a href="/help">Help with delivery</a> <button type="button">Place order</button></main>` const browser = await launch() const page = await (await browser.newContext()).newPage() for (const [name, html] of [['bad page', bad], ['fixed page', good]]) { await page.setContent(html) const { violations } = await new AxeBuilder({ page }).analyze() console.log(`${name}: ${violations.length} violations`) for (const v of violations) { console.log(` ${v.impact.padEnd(8)} ${v.id} (${v.nodes.length})`) } } await browser.close()
n2.mjs: the two pages and the check.
bad page: 7 violations serious color-contrast (1) serious html-has-lang (1) critical image-alt (1) moderate landmark-one-main (1) serious link-name (1) moderate page-has-heading-one (1) moderate region (4) fixed page: 0 violations
Output (Chrome 157, axe-core 4.14.0)
The first page fails on contrast (grey text), the missing lang, the image with no alt, the empty link, and three structural rules about landmarks and headings. After the fixes the report is empty. Two problems in the bad page were not reported at all: the div that acts as a button, and the input that has only a placeholder instead of a label. axe passed both under its rules.
An empty report therefore means "no automatic failures", not "accessible". Tools find mistakes that can be decided from the markup and styles. They cannot tell whether a label makes sense, whether focus order is logical, or whether a dialog traps the keyboard. Put a keyboard pass and a screen reader pass in the definition of done, and run axe in the test suite so the easy failures never return.
Part 3 · Browser support
Deciding which browsers to support
Support is a requirement like any other: it names the browsers and versions the product must work in, and it decides which language and platform features you may use. Writing "all browsers" is not a requirement, because no team can test everything.
A practical policy starts from your own analytics: list the browsers your visitors use, and support the share that matters to the business. For features, Baseline gives a shared yardstick. A feature is newly available once it works in every browser of the core set, and widely available 30 months after that. The core set is Chrome and Edge, Firefox, and Safari, on desktop and mobile where each exists.
| Baseline status | Meaning | How to use it |
|---|---|---|
| Limited availability | missing from at least one core browser | detect it, or keep it optional |
| Newly available | in all core browsers, for under 30 months | use with a fallback for older versions |
| Widely available | in all core browsers for 30 months or more | use freely |
The dates give you a rule you can compute. MDN lists content-visibility as newly available since September 2024, so by the 30-month rule it becomes widely available around March 2027. A written policy might read: "use widely available features directly, use newly available features behind detection, and do not rely on limited ones". That policy is our example, not a standard.
Only Chrome is available for the runs in this course, so output comes from Chrome 157 and Node 24. What other browsers support comes from MDN's compatibility tables, and we say so when we rely on one.
Feature detection
Feature detection asks the browser whether it has a feature before you use it. It is more reliable than reading the browser name from the user agent string, because it tests the thing you care about, and it still works when a browser changes version or pretends to be another one.
The script below runs one set of checks in two places, Node 24 and Chrome 157. JavaScript features are tested by looking for the function, and CSS features by asking CSS.supports.
// Feature detection: the same checks in Chrome and in Node. import { launch } from '../h.mjs' const checks = () => ({ 'CSS container queries': typeof CSS !== 'undefined' && CSS.supports('container-type: inline-size'), 'CSS :has()': typeof CSS !== 'undefined' && CSS.supports('selector(:has(a))'), 'scheduler.yield': typeof scheduler !== 'undefined' && 'yield' in scheduler, 'Temporal': typeof Temporal !== 'undefined', 'Object.groupBy': typeof Object.groupBy === 'function', 'Array toSorted': typeof [].toSorted === 'function', 'Intl.Segmenter': typeof Intl.Segmenter === 'function', 'View Transitions': typeof document !== 'undefined' && 'startViewTransition' in document, }) const inNode = checks() const browser = await launch() const page = await browser.newPage() const inChrome = await page.evaluate(checks) console.log('feature'.padEnd(22) + 'Chrome'.padEnd(7) + 'Node') for (const key of Object.keys(inNode)) { const c = String(inChrome[key]).padEnd(7) console.log(key.padEnd(22) + c + inNode[key]) } await browser.close()
n4.mjs: the same checks in Chrome and Node.
feature Chrome Node CSS container queries true false CSS :has() true false scheduler.yield true false Temporal true false Object.groupBy true true Array toSorted true true Intl.Segmenter true true View Transitions true false
Output (Chrome 157 and Node 24)
Chrome 157 has every feature in the list. Node 24 has the three that are part of the language (Object.groupBy, toSorted, Intl.Segmenter) and none of the browser ones, which is expected: it has no CSS and no document. It also lacks Temporal, the modern date and time API. MDN marks Temporal as limited availability, so code that uses it needs a check first, even in a browser that has it today.
Test the exact thing you use. scheduler.yield is a function on a scheduler object, so the check is typeof scheduler !== 'undefined' && 'yield' in scheduler. A check on a neighbouring feature may be true when yours is not.
Progressive enhancement and polyfills
Progressive enhancement builds the page in layers. The first layer is HTML that works in any browser: links navigate and forms submit. CSS and JavaScript then improve it where the browser supports them. If a script fails to load or a feature is missing, the user still completes the task, only with less polish.
A polyfill is code that adds a missing feature in JavaScript. It is a fallback that costs bytes and run time, so load it only when detection says it is needed. The script below deletes Object.groupBy to pretend the runtime lacks it, then uses a small hand-written version in its place.
// A guarded fallback: the built-in when present, else a small copy. const orders = [ { city: 'Pune', total: 4 }, { city: 'Surat', total: 2 }, { city: 'Pune', total: 7 }, ] const fallbackGroupBy = (list, key) => { const out = {} for (const item of list) (out[key(item)] ??= []).push(item) return out } const native = Object.groupBy(orders, (o) => o.city) delete Object.groupBy // pretend this runtime lacks it const groupBy = Object.groupBy ?? fallbackGroupBy const result = groupBy(orders, (o) => o.city) const same = JSON.stringify(result) === JSON.stringify(native) console.log('built-in after delete:', typeof Object.groupBy) console.log('fallback gives the same groups:', same) for (const [city, list] of Object.entries(result)) { console.log(city, list.map((o) => o.total).join(' + ')) }
n5.mjs: use the built-in when present, otherwise a copy.
built-in after delete: undefined fallback gives the same groups: true Pune 4 + 7 Surat 2
Output (Node 24)
The fallback returns the same groups as the built-in. The line Object.groupBy ?? fallbackGroupBy is the whole pattern: prefer the native function, which is faster and maintained by the browser, and fall back only where it is absent. For larger polyfills the same check guards a dynamic import(), so browsers that have the feature never download the code.
CSS has the same idea in @supports, which applies a block only when the browser understands a declaration. Prefer a design where the unsupported case looks plainer but still works, and avoid one where the unsupported case is broken.
Polyfills fill gaps in JavaScript APIs. They do not change syntax: a browser that cannot parse a new syntax feature throws before any code runs. A build step that rewrites new syntax into older syntax handles that, and the supported-browser list decides how far it rewrites.
Part 4 · Localisation and internationalisation
Two words for one job
Internationalisation (i18n) is designing the software so it can work in many languages and regions without code changes. Localisation (l10n) is the work of adapting it to one of them: translated text, local formats, and checks by someone who reads the language. The abbreviations count the letters between the first and last.
Indian products meet this early. English and Hindi can appear on the same screen, numbers are grouped as lakhs and crores, and a name can be in Devanagari, Tamil or Telugu script. Requirements should say which locales ship, which scripts the text fields must accept, and whether any language is written right to left.
The browser and Node both include the Intl API, which formats numbers, currency, dates, lists and plurals by locale. A locale is a language and region tag such as en-IN or hi-IN. The script formats one number and one date for three locales.
// Intl formats for English (India), Hindi (India) and English (US). const amount = 12345678.5 const when = new Date('2026-11-22T09:30:00Z') const num = (l, o) => new Intl.NumberFormat(l, o).format(amount) const date = (l) => new Intl.DateTimeFormat(l, { dateStyle: 'long', timeZone: 'Asia/Kolkata', }).format(when) for (const locale of ['en-IN', 'hi-IN', 'en-US']) { console.log(locale) console.log(' number ', num(locale)) const inr = { style: 'currency', currency: 'INR' } console.log(' rupees ', num(locale, inr)) console.log(' date ', date(locale)) }
n6.mjs: formats by locale.
en-IN number 1,23,45,678.5 rupees ₹1,23,45,678.50 date 22 November 2026 hi-IN number 1,23,45,678.5 rupees ₹1,23,45,678.50 date 22 नवंबर 2026 en-US number 12,345,678.5 rupees ₹12,345,678.50 date November 22, 2026
Output (Node 24), first twelve lines
English and Hindi for India both group digits as 1,23,45,678.5, because the grouping follows the region. The en-US lines group in threes. The date names the month in the language of the locale. Hand-written formatting, such as toFixed(2) plus a comma regex, gets the Indian grouping wrong, so use Intl.NumberFormat and pass the user's locale.
Plurals and lists
Plural rules differ by language, so count === 1 ? 'item' : 'items' is only correct for some of them. Intl.PluralRules returns a plural category for a number, such as one or other, and a message table supplies a form for each category the language uses. English uses one and other. The same call runs for Hindi.
const category = (l, n) => new Intl.PluralRules(l).select(n) for (const l of ['en-IN', 'hi-IN']) { const got = [0, 1, 2].map((n) => category(l, n)).join(', ') console.log(`plural categories for 0, 1, 2 in ${l}: ${got}`) } const cities = ['Pune', 'Surat', 'Kochi'] for (const l of ['en-IN', 'hi-IN']) { console.log(new Intl.ListFormat(l).format(cities)) } const ago = new Intl.RelativeTimeFormat('hi-IN', { numeric: 'auto' }) console.log(ago.format(-1, 'day'))
n6.mjs: plural categories, lists and relative time.
plural categories for 0, 1, 2 in en-IN: other, one, other plural categories for 0, 1, 2 in hi-IN: one, one, other Pune, Surat and Kochi Pune, Surat, और Kochi कल
Output (Node 24), last five lines of the same run
In English, zero takes the same form as plural: "0 items". In Hindi, zero belongs to the category one, so a rule that tests n === 1 puts it in the wrong group. The list formatter joins with the right word for each language, and the relative time formatter turns -1 day into the word for "yesterday". None of this is in your code. The locale data ships with the runtime.
A translation file should therefore hold a message per plural category, keyed by locale, and call PluralRules to choose. Keep whole sentences in the message, not fragments joined in code, because word order differs between languages.
Direction and text length
Some scripts, such as Arabic and Hebrew, run right to left. The W3C advice is to put the base direction in markup with the dir attribute, on the html element for the whole page, and never to apply it with CSS, so the information survives when the stylesheet does not load. For text whose direction you do not know, such as user input, dir="auto" picks it from the first strongly directional character.
Layout should use logical properties, which refer to the start and end of the line instead of left and right. margin-inline-start is the left margin in a left-to-right page and the right margin in a right-to-left one. The script measures both versions of a box.
const browser = await launch() const page = await browser.newPage() const box = 'width:100px;height:10px;background:#000' const markup = (dir) => `<html dir="${dir}"> <body style="margin:0;width:400px"> <div id="phys" style="margin-left:50px;${box}"></div> <div id="logic" style="margin-inline-start:50px;${box}"></div>` for (const dir of ['ltr', 'rtl']) { await page.setContent(markup(dir)) const at = await page.evaluate(() => { const x0 = document.body.getBoundingClientRect().left const left = (id) => document.getElementById(id).getBoundingClientRect().left - x0 return `phys ${left('phys')}, logic ${left('logic')}` }) console.log(`dir=${dir}: px from the body's left edge: ${at}`) }
n7.mjs: a physical and a logical margin, in both directions.
dir=ltr: px from the body's left edge: phys 50, logic 50 dir=rtl: px from the body's left edge: phys 300, logic 250
Output (Chrome 157)
In the left-to-right page both boxes start 50 px from the left. In the right-to-left page the box with margin-left has its margin on the wrong side: it is 300 px from the left, flush against the right edge of the 400 px body. The logical one keeps its 50 px gap on the right, so it sits 250 px from the left. One logical property gives the correct mirror image.
Text grows in translation
Text length changes too. The second part of the script puts an English label and a Hindi label into buttons, first with a fixed width of 96 px and then with a minimum width.
await page.setContent(`<style> button { font: 16px sans-serif; padding: 4px 8px } .fixed { width: 96px; overflow: hidden; white-space: nowrap } .flex { min-inline-size: 96px }</style> <button class="fixed" id="f1">Confirm</button> <button class="fixed" id="f2">भुगतान की पुष्टि करें</button> <button class="flex" id="g1">Confirm</button> <button class="flex" id="g2">भुगतान की पुष्टि करें</button>`) for (const id of ['f1', 'f2', 'g1', 'g2']) { const r = await page.evaluate((i) => { const e = document.getElementById(i) return { cut: e.scrollWidth > e.clientWidth, w: e.offsetWidth } }, id) const note = r.cut ? 'text is clipped' : 'text fits' console.log(id, 'width', r.w, note) } await browser.close()
n7.mjs: fixed width against minimum width.
f1 width 96 text fits f2 width 96 text is clipped g1 width 96 text fits g2 width 141 text fits
Output (Chrome 157), last four lines
The longer Hindi label is clipped in the fixed button and fits in the flexible one, which grew to 141 px. Translations are often longer than the English they replace, so design for text to grow: avoid fixed widths on labels, allow wrapping, and test with the longest strings. Also set the lang attribute on the page. Screen readers use it to choose a pronunciation, and WebAIM found it missing on 13.5% of home pages.
Why use Intl.NumberFormat instead of formatting numbers by hand?
- Grouping, decimal marks and currency symbols follow the locale, such as 1,23,45,678.5 for India.
- The locale data ships with the runtime, so your code does not carry the rules.
In Hindi, which plural category does 0 fall in, and why does it break n === 1 rules?
- The category
one, as the run showed. - A hand-written test for exactly 1 picks the wrong form for languages whose rules differ from English.
A button has margin-left: 8px and the page is switched to right to left. What goes wrong and what is the fix?
Part 5 · Maintainability
Cost of change
A frontend lives for years and is edited by many people. Maintainability is how cheaply and safely the code can be changed. It is a requirement because it cannot be added at the end: it comes from structure decided at the start, and it shows up as the time it takes to change a screen without breaking another.
Three habits carry most of it: clear boundaries between modules, shared contracts that the compiler checks, and tests that describe what a user sees. This lesson takes them in turn.
A module boundary is a rule about what a part of the code may depend on. A feature folder such as cart exposes a small public file and keeps everything else private. Other features import only from that file. Then the inside of cart can be rewritten without touching its neighbours.
src/
cart/
index.ts public: what other features may import
CartView.ts
cartStore.ts private
search/
index.ts
SearchBox.ts
shared/
http.ts used by every feature
money.tsA layout to aim for. Features import each other only through index.ts.
The direction matters as much as the folders. Features may use shared, but shared must never import a feature, or the dependencies loop and nothing can move alone. A lint rule or a test over the import graph keeps the rule alive after the people who agreed it have left.
Contracts and versions
Parts of a frontend talk to each other through interfaces: a function signature, a component's props, an API response. A typed contract writes that shape down in a type that the compiler checks on both sides. The next two files show a shared package renaming a field and a consumer that still uses the old name.
// the shared package renamed total to totalPaise export type OrderSummary = { id: string totalPaise: number }
contract.ts: the shared type.
import type { OrderSummary } from './contract.ts' export function showTotal(order: OrderSummary): string { return `Total: ${order.total / 100} rupees` }
consumer.ts: the old field name.
consumer.ts(4,26): error TS2339: Property 'total' does not exist on type 'OrderSummary'.
Output (tsc 7.0.2 with strict on, long line wrapped)
The compiler points at the exact line before anything ships. Without the type, the old code keeps running and reads a field that no longer exists. The next file prints what a user would see.
// What a consumer prints when a renamed field is read as before. const order = { id: 'ord-1', totalPaise: 5400 } // the new shape console.log(`Total: ${order.total / 100} rupees`)
n10.mjs: the same line without a compiler.
Total: NaN rupees
Output (Node 24)
The page would show "Total: NaN rupees". A type checks the code at build time only. Data arriving over the network still needs a check at run time, which the TypeScript chapter covers.
When the shared code is a package used by several apps, a version number tells consumers how much to worry. Semantic versioning (semver) uses MAJOR.MINOR.PATCH: a bug fix bumps the patch, a backward-compatible addition bumps the minor, and a breaking change bumps the major and resets the others to zero. Versions starting at 0, such as 0.4.2, mean the API may change at any time.
| Change to the shared package | Bump | Example |
|---|---|---|
| fix a bug without changing the API | patch | 2.3.4 to 2.3.5 |
Tests that survive refactors
A test that depends on how the code is built breaks when the code is rewritten even though the behaviour is the same. A test that describes what the user can see and do survives. The Playwright documentation recommends testing user-visible behaviour and using locators that survive changes to the DOM: role, text and test id before CSS or XPath.
The script below has one button in two versions of a page. The second version has a different structure and different class names, as after a restyle. Each version is tested twice, once by CSS class and once by role and accessible name.
// Two tests of one button: by CSS class and by role and name. import { launch } from '../h.mjs' const v1 = `<div class="card"><button class="btn-primary" onclick="out.textContent='1 item'">Add to cart</button></div> <p id="out"></p>` const v2 = `<section class="product"><div class="actions"> <button class="cta" onclick="out.textContent='1 item'">Add to cart </button></div></section><p id="out"></p>` const byClass = (page) => page.locator('.btn-primary') const byRole = (page) => page.getByRole('button', { name: 'Add to cart' }) const browser = await launch() const page = await browser.newPage() for (const [version, html] of [['v1', v1], ['v2, restyled', v2]]) { const finders = [['by class', byClass], ['by role ', byRole]] for (const [how, find] of finders) { await page.setContent(html) let result = 'pass' try { await find(page).click({ timeout: 1000 }) } catch { result = 'FAIL, button not found' } console.log(version.padEnd(13), how, result) } } await browser.close()
n8.mjs: two ways to find the same button.
v1 by class pass v1 by role pass v2, restyled by class FAIL, button not found v2, restyled by role pass
Output (Chrome 157)
Both tests pass on version 1. After the restyle, the class-based test fails although nothing a user can see has changed, and the role-based test still passes. The role locator also checks something useful as a side effect: it can only find the control if it really exposes a button role and the name "Add to cart", which is the same information a screen reader uses.
Tests like this make refactoring safe, and they pair with the accessibility checks from the accessibility lesson. Keep each test independent of the others, and keep a few slower end-to-end tests for the main journeys, such as search, add to cart and pay, with many faster tests below them.
All chapters · Previous: Machine Coding Practice in Plain JavaScript