Courses / Frontend System Design, with JavaScript Foundations / Chapter 8
Module 3 · Browser Foundations · Chapter 8 of 21
Machine Coding Practice in Plain JavaScript
Builds on Values, Coercion, Scope and Closures, this, Prototypes and Classes, Promises, Async Code and the Browser Event Loop and The DOM, Events and Observers. Next up: Non-functional Requirements.
Part 1 · The round and a place to practise
What the round asks
A machine coding round hands you a small spec, such as a debounce utility or an autocomplete box, and a fixed amount of time to deliver working code. The format varies between organisations, so treat everything here as a practice schedule and not as a rule.
The task is usually small enough to finish in about an hour and large enough to need design: a few functions or one component, with edge cases the spec does not spell out. A reviewer reading the result tends to look at the same things. Does it run on the given inputs? Does it survive the awkward ones, such as an empty list, a repeated call or a request that fails? Is the code split into pieces with clear names? Did you check it yourself, and can you explain the choices?
The drills in this chapter are built around that. Each utility in the next three lessons is under 40 lines, and the autocomplete widget in the last lesson is 72. All of them have tests that pass in the output shown. Writing the tests first, or at least alongside, is what makes the last ten minutes of a timed task calm, because you know what works.
The schedule below is a plan for one hour. It is our suggestion for practice, not a rule from any organisation.
| Minutes | Do this | Output |
|---|---|---|
| 0 to 5 | Read the spec twice and list the edge cases | a short written list |
| 5 to 10 | Decide the function signature or component props | the public interface |
| 10 to 35 | Build the core path and run it | working main behaviour |
| 35 to 50 | Handle the edge cases from the list |
A test loop with node:test
Node ships a test runner, so the drills need no extra packages. A test file imports test from node:test and the assertion functions from node:assert/strict. The command node --test finds and runs the files, and --test-reporter=spec prints one line per test.
export function clamp(value, min, max) { return Math.min(Math.max(value, min), max) }
import { test } from 'node:test' import assert from 'node:assert/strict' import { clamp } from './clamp.mjs' test('clamp keeps a value inside the range', () => { assert.equal(clamp(5, 0, 10), 5) assert.equal(clamp(-3, 0, 10), 0) assert.equal(clamp(42, 0, 10), 10) }) test('clamp handles NaN by returning NaN', () => { assert.ok(Number.isNaN(clamp(NaN, 0, 10))) })
✔ clamp keeps a value inside the range (0.6255ms) ✔ clamp handles NaN by returning NaN (0.1498ms) ℹ tests 2 ℹ pass 2 ℹ fail 0 ℹ duration_ms 90.2244
Output (Node 24, node:test)
Each test call runs its function, and a thrown error fails it. assert/strict makes equal compare with Object.is, which is === except for NaN and signed zeros, and makes deepEqual compare structures strictly, so a wrong value fails loudly. The summary at the end counts the passes. The tests in the later lessons follow the same shape, and some use the runner's mock helper, which is introduced with the first drill that needs it.
The habit to build is to run the tests after every change, not at the end. A one-line change that breaks a test is easy to find when the last run was a minute ago.
A browser check with Playwright
The last drill of this chapter is a widget that runs in a page, so its tests need a real browser. The playwright-core package drives an installed Chrome without downloading its own, and it fits inside a node:test file. The test opens a page, interacts as a user would, and asserts on what the page shows.
import { test, before, after } from 'node:test' import assert from 'node:assert/strict' import { chromium } from 'playwright-core' let browser, page before(async () => { browser = await chromium.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', }) page = await browser.newPage() }) after(() => browser.close()) test('the counter button counts clicks', async () => { await page.setContent(`<button id="c">0</button> <script> c.addEventListener('click', () => { c.textContent = Number(c.textContent) + 1 }) </script>`) await page.click('#c') await page.click('#c') assert.equal(await page.textContent('#c'), '2') })
✔ the counter button counts clicks (585.0245ms) ℹ tests 1 ℹ pass 1 ℹ fail 0 ℹ duration_ms 6007.9121
Output (Node 24, node:test)
before and after open and close the browser once for the file. The test sets the page content, clicks the button twice with real input events and reads the text back. Waiting for the page, not for a fixed delay, is the rule: Playwright waits for an element to be ready before it clicks, and later tests wait for a selector or a response instead of sleeping.
Starting Chrome adds time to every run, so browser tests are slower than plain ones. Keep the logic in plain functions that you can test fast, as the utility drills do, and use the browser only for what needs one, such as keyboard handling and focus.
Why write the tests alongside the code in a timed task?
- You find out which behaviours already work, so the last minutes go to the open edge cases instead of to re-checking everything by hand.
Which command runs the test files with one line per test?
node --test --test-reporter=spec, optionally followed by file names.
Part 2 · Debounce and throttle
Two ways to slow a function down
Some events fire far more often than the work they trigger should run. A search box fires on every keystroke, a window fires resize dozens of times as you drag, and a user may double-click a save button. Two wrappers limit how often the work runs.
Debounce waits for quiet. Each call restarts a timer, and the wrapped function runs only when no call has arrived for the full wait. It suits a search box: the user types a word, pauses, and one request goes out. Throttle runs at most once per window. It suits scrolling or dragging, where you want regular updates during the action and not one at the end.
Both take two options that decide which calls count. Leading means run at the start of the burst, at once. Trailing means run at the end, with the most recent arguments. The versions in this lesson follow the usual convention: debounce defaults to trailing only, and throttle defaults to both, so the first call responds immediately and the last call of a burst is not lost.
| Debounce | Throttle | |
|---|---|---|
| Runs when | no call for wait ms | at most once per wait ms window |
| Default | trailing only | leading and trailing |
| Best for | search boxes, validation, autosave | scroll, resize, drag |
| Must also offer | cancel | cancel |
Both wrappers must keep the caller's this and pass the latest arguments, because a wrapped method such as form.save would otherwise lose its object. They should also offer cancel, so a component can drop a pending call when it unmounts or when the user presses Escape.
The debounce implementation
The state is one timer plus the last arguments and this. Every call restarts the timer. When the timer fires, the trailing call runs with the stored values. A leading call runs straight away when no timer is pending, and it does not store arguments, so the trailing call fires only if another call arrives during the wait.
export function debounce(fn, wait, options = {}) { const { leading = false, trailing = true } = options let timer = null let lastArgs let lastThis function debounced(...args) { const idle = timer === null clearTimeout(timer) timer = setTimeout(() => { timer = null if (trailing && lastArgs) { const [args, self] = [lastArgs, lastThis] lastArgs = lastThis = undefined fn.apply(self, args) } }, wait) if (leading && idle) fn.apply(this, args) else [lastArgs, lastThis] = [args, this] } debounced.cancel = () => { clearTimeout(timer) timer = null lastArgs = lastThis = undefined } return debounced }
Two details are easy to miss. The function expression uses this from the call, so debounced must be a regular function and not an arrow. And idle is read before the timer is replaced, because it decides whether this call starts a new burst.
The throttle implementation
Throttle opens a window with a timer at the first call. During the window, calls only record their arguments. When the window ends, a stored call runs and opens a new window, which spaces runs by at least one full wait even in a steady stream of calls.
export function throttle(fn, wait, options = {}) { const { leading = true, trailing = true } = options let timer = null let pending // { args, self } waiting for the window to end function openWindow() { timer = setTimeout(() => { timer = null if (trailing && pending) { const { args, self } = pending pending = undefined fn.apply(self, args) openWindow() } }, wait) } function throttled(...args) { const idle = timer === null if (idle) openWindow() if (idle && leading) fn.apply(this, args) else pending = { args, self: this } } throttled.cancel = () => { clearTimeout(timer) timer = null pending = undefined } return throttled }
The difference from debounce is in openWindow. A debounced call restarts the timer on every call, so a constant stream postpones the run forever. A throttled call never restarts the window, so a constant stream still produces one run per window.
Testing time with fake timers
Real timers make timing tests slow and flaky. The mock helper in node:test replaces them. mock.timers.enable({ apis: ['setTimeout'] }) fakes setTimeout, and mock.timers.tick(ms) moves the fake clock forward and runs whatever came due. The tests then run in a few milliseconds and give the same answer every time. Reset the mock after each test, here with an afterEach hook.
import { test, mock, afterEach } from 'node:test' import assert from 'node:assert/strict' import { debounce } from './debounce.mjs' afterEach(() => mock.timers.reset()) function setup(options) { mock.timers.enable({ apis: ['setTimeout'] }) const calls = [] const fn = debounce((...args) => calls.push(args), 300, options) return { calls, fn } } test('only the last call in a burst runs, after the wait', () => { const { calls, fn } = setup() fn('h'); mock.timers.tick(100) fn('he'); mock.timers.tick(100) fn('hel') mock.timers.tick(299) assert.deepEqual(calls, []) mock.timers.tick(1) assert.deepEqual(calls, [['hel']]) })
The setup and the first test; the file has four.
✔ only the last call in a burst runs, after the wait (2.282ms) ✔ leading runs at once and trailing only if called again (0.8881ms) ✔ cancel drops the pending call (0.2842ms) ✔ keeps this and the latest arguments (0.2958ms) ✔ leading call runs at once, the rest wait for the window (1.9924ms) ✔ calls spaced one window apart each run (0.7795ms) ✔ trailing false drops the last call of a burst (0.2732ms) ✔ cancel clears the window and the pending call (0.2709ms) ℹ tests 8 ℹ pass 8 ℹ fail 0 ℹ duration_ms 93.8782
Output (Node 24, node:test)
The first test types h, he and hel with 100 ms gaps. Just before the wait has passed from the last call nothing has run, and one millisecond later exactly one call has, with the last value. The other tests cover leading and trailing, cancel, and this.
A test that cannot fail proves nothing. To check these tests, they were run against a naive version that sets a new timer on every call and never clears the old one.
✖ only the last call in a burst runs, after the wait (3.2271ms) test at naive.test.mjs:14:1 ✖ only the last call in a burst runs, after the wait (3.2271ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal: + actual - expected + [ + [ + 'h' + ], + [ + 'he' + ] + ] - []
Output (Node 24, naive version, first test only)
Part 3 · Promise utilities
Rebuilding Promise.all
Promise helpers are a common drill because they test whether you understand how promises settle. Promise.all takes a list, waits for every item and resolves with the results in input order. If any item rejects, the whole promise rejects with the first rejection.
The version below follows those rules. It keeps a results array and a count of items left. Each item is wrapped in Promise.resolve, so plain values and promises are treated alike. When an item resolves, its value goes into its own slot and the count drops. When the count reaches zero the outer promise resolves. A rejection calls reject, and because a promise settles only once, later calls to resolve or reject do nothing.
export function promiseAll(items) { return new Promise((resolve, reject) => { const list = [...items] const results = new Array(list.length) let left = list.length if (left === 0) resolve(results) list.forEach((item, i) => { Promise.resolve(item).then((value) => { results[i] = value if (--left === 0) resolve(results) }, reject) }) }) }
promiseAll, from promises.mjs.
The empty list is the classic edge case. With no items, nothing would ever call resolve, so the code resolves at once. Writing [...items] first also lets the function accept any iterable, such as a Set, as the native one does.
The tests do not rely on what the author believes Promise.all does. They run the native function on the same input and compare the two outcomes, success or failure, with settle, which turns each promise into a value that can be compared.
Retry with backoff and jitter
Networks fail for short moments, so a request is often worth repeating. Repeating at once is a poor idea: if a server is overloaded, a thousand clients retrying together keep it overloaded. Exponential backoff waits longer after each failure, doubling a base delay up to a cap. Jitter randomises the wait so clients do not retry in step. The version here uses full jitter: the wait is a random fraction of the current ceiling.
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) export async function retry(task, options = {}) { const { retries = 3, baseMs = 100, capMs = 2000 } = options const { random = Math.random, wait = sleep } = options for (let attempt = 0; ; attempt++) { try { return await task(attempt) } catch (error) { if (attempt >= retries) throw error const ceiling = Math.min(capMs, baseMs * 2 ** attempt) await wait(random() * ceiling) } } }
sleep and retry, from promises.mjs.
The function takes random and wait as options with real defaults. That one choice makes it testable: a test passes random: () => 1 and a wait that records the delay and returns at once, and then checks the exact numbers. Code that calls Math.random and setTimeout directly can only be tested with real delays and luck.
The task receives the attempt number, which helps with logging. After the last allowed retry the loop rethrows the last error, so the caller sees the real failure and not a vague one.
A concurrency limiter
Starting 500 requests at once can exhaust sockets, memory or an API's rate limit. A concurrency limiter runs at most N tasks at a time and queues the rest. It is the core of helpers such as p-limit, and it is short enough to write in a timed round.
The design is a counter of active tasks and a queue. createLimiter(max) returns a function that takes a task and returns a promise for its result. Calling it queues the task and tries to start it. next starts a task if fewer than max are running. When a task settles, in either way, finally lowers the count and calls next again, which pulls the next task from the queue.
export function createLimiter(max) { let active = 0 const queue = [] function next() { if (active >= max || queue.length === 0) return active++ const { task, resolve, reject } = queue.shift() Promise.resolve() .then(task) .then(resolve, reject) .finally(() => { active-- next() }) } return (task) => new Promise((resolve, reject) => { queue.push({ task, resolve, reject }) next() }) } export const mapLimit = (items, max, fn) => { const run = createLimiter(max) return Promise.all(items.map((item, i) => run(() => fn(item, i)))) }
Starting the task inside Promise.resolve().then(task) turns a synchronous throw inside task into a rejection, so one failing task cannot break the limiter. mapLimit applies it to a list and keeps results in input order because Promise.all does.
✔ never runs more than max tasks at once (44.453ms) ✔ a failing task does not block the queue (0.7053ms) ✔ mapLimit keeps result order and passes the index (28.1872ms) ✔ promiseAll matches Promise.all: empty list (1.4247ms) ✔ promiseAll matches Promise.all: plain values (0.7196ms) ✔ promiseAll matches Promise.all: input order kept (76.1827ms) ✔ promiseAll matches Promise.all: first rejection (31.2867ms) ✔ promiseAll matches Promise.all: any iterable (0.5035ms) ✔ retry backs off exponentially and then succeeds (0.4442ms) ✔ retry caps the delay and scales it by the jitter (0.3417ms) ✔ retry throws the last error when attempts run out (0.3117ms) ℹ tests 11 ℹ pass 11 ℹ fail 0 ℹ duration_ms 217.414
Output (Node 24, node:test)
The limiter test starts eight tasks with a limit of three and records the peak number running together. It must be exactly three: fewer would mean the queue is too cautious, and more would mean the limit is broken. Another test shows a failing task does not block those behind it.
Part 4 · Data utilities
Deep clone with cycles
Copying nested data safely comes up in state management, undo stacks and tests. A shallow copy, such as { ...obj }, copies the top level only, so nested objects stay shared and a change to one copy shows in the other. A deep clone copies every level.
The browser and Node have a built-in one, structuredClone, and a custom version is tested against it. The approach is recursive. Primitives return as they are. Dates, maps and sets get new containers. Arrays and plain objects are rebuilt key by key. The hard part is a cycle, an object that refers back to itself, which would recurse forever. A WeakMap from each original to its copy solves it: before descending, record the copy, and if the same original appears again, return the recorded copy.
export function deepClone(value, seen = new WeakMap()) { if (typeof value === 'function') { throw new TypeError('cannot clone a function') } if (value === null || typeof value !== 'object') return value if (seen.has(value)) return seen.get(value) if (value instanceof Date) return new Date(value.getTime()) let copy if (value instanceof Map) copy = new Map() else if (value instanceof Set) copy = new Set() else copy = Array.isArray(value) ? [] : {} seen.set(value, copy) const again = (item) => deepClone(item, seen) if (value instanceof Map) { for (const [k, v] of value) copy.set(again(k), again(v)) } else if (value instanceof Set) { for (const v of value) copy.add(again(v)) } else { for (const key of Object.keys(value)) copy[key] = again(value[key]) } return copy }
Class instances come out as plain objects with the same own properties, which is what structuredClone does too, since it does not keep prototypes. Functions cannot be cloned.
✔ deepClone matches structuredClone: nested (1.4156ms) ✔ deepClone matches structuredClone: date (1.0924ms) ✔ deepClone matches structuredClone: map (2.9891ms) ✔ deepClone matches structuredClone: set (0.3248ms) ✔ deepClone matches structuredClone: class instance (4.6188ms) ✔ deepClone copies deeply and keeps cycles (1.6246ms) ✔ on, once, off and emit (1.3607ms) ✔ off with the original function removes a once handler (0.1252ms) ✔ a handler can remove itself during emit (0.1345ms) ✔ get reads dotted and bracket paths (0.7918ms) ℹ tests 10 ℹ pass 10 ℹ fail 0 ℹ duration_ms 112.3423
Output (Node 24, node:test, all three files)
An event emitter
An event emitter lets parts of a program talk without knowing each other: one side calls emit, the other registered a handler with on. The interface is small. on adds a handler and returns a function that removes it. off removes one. once runs a handler a single time. emit calls the handlers and says whether there were any.
export class Emitter { #handlers = new Map() on(type, fn) { const list = this.#handlers.get(type) ?? [] this.#handlers.set(type, [...list, fn]) return () => this.off(type, fn) } once(type, fn) { const wrapper = (...args) => { this.off(type, wrapper) fn(...args) } wrapper.original = fn return this.on(type, wrapper) } off(type, fn) { const list = this.#handlers.get(type) ?? [] const at = list.findIndex((h) => h === fn || h.original === fn) if (at >= 0) this.#handlers.set(type, list.toSpliced(at, 1)) } emit(type, ...args) { const list = this.#handlers.get(type) ?? [] for (const handler of list) handler(...args) return list.length > 0 } }
Three details matter. First, handlers are stored in arrays that are replaced, not changed, on each add or remove. emit loops over the array it started with, so a handler that removes itself, or adds another, cannot make the loop skip or repeat a handler. Second, once wraps the handler and remembers the original in wrapper.original, so off(type, original) still finds it. Third, the private field #handlers keeps the map out of reach of callers.
The tests check each of those: a once handler runs one time, off works with the original function, and a handler can remove itself while the event is being emitted without the next handler being skipped.
Reading a value by path
Utilities such as lodash's get read a nested value from a path string and return a default if any step is missing. The path user.tags[1] means: key user, key tags, index 1. The code first turns the bracket form into dots, then splits, so both forms give a list of keys. The walk stops with the default at the first null or undefined.
export function get(object, path, fallback) { const keys = Array.isArray(path) ? path : path.replace(/\[(\w+)\]/g, '.$1').split('.').filter(Boolean) let current = object for (const key of keys) { if (current === null || current === undefined) return fallback current = current[key] } return current === undefined ? fallback : current }
The last line matters: it returns the default only when the value is undefined. A stored 0, an empty string or false is a real value and must come back as it is. The test checks user.zero returns 0 even with a default given, and that a property explicitly set to undefined does return the default.
All three utilities follow the plan from the first lesson: write the interface, list the edge cases, test each. The edge cases here were cycles, functions, self-removal during emit, once removal and falsy values. Spotting them before coding is where the time goes in a timed task.
Why does deepClone need a WeakMap?
- It records each original with its copy, so a cycle returns the existing copy instead of recursing forever.
Why does emit loop over a list that off replaces instead of changing?
- A handler that removes itself during
emitwould otherwise shift the array and make the loop skip the next handler.
Why must get check for undefined and not use ||?
- Values such as
0,falseand an empty string are real data. Onlyundefinedmeans the path was missing.
Part 5 · An autocomplete widget
The spec and the server
The last drill puts the earlier ones to work. The task is a text field that suggests city names as you type. The spec fits on a card: show suggestions for the typed prefix, send at most one request per pause in typing, never show an answer for an older query, and work from the keyboard.
The backing server is a local stub with a list of eleven cities. It has a deliberate flaw to expose a race: it answers short queries more slowly, 500 ms for one letter and 300 ms for two. A reply to an older, shorter query can therefore arrive after the reply to a newer one, which is how out-of-order replies happen on real networks.
export function startServer(port) { const log = [] const server = createServer(async (req, res) => { const url = new URL(req.url, 'http://x') if (url.pathname === '/search') { const q = url.searchParams.get('q').toLowerCase() log.push(q) // shorter queries answer more slowly, so replies can arrive late await wait(Math.max(0, 700 - 200 * q.length)) const hits = CITIES.filter((c) => c.toLowerCase().startsWith(q)) res.setHeader('content-type', 'application/json') res.end(JSON.stringify(hits)) } else if (FILES[url.pathname]) { const html = url.pathname === '/' const type = html ? 'text/html' : 'text/javascript' res.setHeader('content-type', type) const file = new URL('../' + FILES[url.pathname], import.meta.url) res.end(await readFile(file)) } else { res.statusCode = 404 res.end() } }) const ready = (ok) => server.listen(port, '127.0.0.1', () => ok()) return new Promise(ready).then(() => ({ server, log })) }
The /search handler and the delay rule, from server.mjs.
The server also keeps a list of the queries it received, which the tests use to count requests. The static files for the page are served by the same program, on port 55812.
Fetching with debounce and cancellation
The widget reuses debounce from the first drill so a burst of keystrokes sends one request. Debounce cannot fix a race by itself, though: a request already in flight when the user types again is not stopped. That is the job of AbortController.
Each search first aborts the previous request, then creates a new controller and passes its signal to fetch. An aborted fetch rejects with an error named AbortError. That is not a failure, only a request that was dropped on purpose, so the catch block ignores it and rethrows anything else.
function render(items) { list.replaceChildren(...items.map((text, i) => { const li = document.createElement('li') li.setAttribute('role', 'option') li.id = `${list.id}-${i}` li.textContent = text return li })) list.hidden = items.length === 0 input.setAttribute('aria-expanded', String(items.length > 0)) setActive(-1) } async function search(query) { if (!query) return render([]) if (abortStale) controller?.abort() controller = new AbortController() try { const url = `${endpoint}?q=${encodeURIComponent(query)}` const res = await fetch(url, { signal: controller.signal }) render(await res.json()) } catch (error) { if (error.name !== 'AbortError') throw error } } const debounced = debounce(search, wait) input.addEventListener('input', () => debounced(input.value.trim()))
Rendering and searching; the file is 72 lines.
render builds one li with the role option for each suggestion and sets aria-expanded to match whether the list is shown. close cancels the pending debounce, aborts any request in flight and empties the list, so pressing Escape or choosing an item cannot be followed by a late result that reopens the list.
Keyboard and ARIA
A suggestion box is a combobox, and assistive technology relies on specific attributes to describe it. The W3C's ARIA Authoring Practices Guide lists them. The input has role="combobox". aria-controls points at the popup, which has role="listbox". aria-expanded is true while the popup is visible. aria-autocomplete="list" says suggestions are offered as a list. Each option has role="option", and aria-selected is true on the current one.
Focus stays in the input while the user moves through the list, so the input cannot point at the current option with DOM focus. It uses aria-activedescendant, set to the id of the active option. Assistive technology can then present that option as the focused one, while typing still goes to the input.
| Key | What it does here | Pattern |
|---|---|---|
| Down Arrow | next option, from none to the first, stops at the last | APG |
| Up Arrow | previous option, from none to the last, stops at the first | optional in APG |
| Enter | copies the active option into the input and closes | APG |
| Escape | closes the list | APG |
The arrows stop at the ends of the list instead of wrapping round. For a listbox popup, the APG says that at the last option Down Arrow either returns focus to the combobox or does nothing, and the same for Up Arrow at the first. This widget takes the second choice.
input.addEventListener('keydown', (e) => { const count = options().length if (e.key === 'ArrowDown' && count) { e.preventDefault() setActive(Math.min(active + 1, count - 1)) } else if (e.key === 'ArrowUp' && count) { e.preventDefault() setActive(active < 0 ? count - 1 : Math.max(active - 1, 0)) } else if (e.key === 'Enter' && active >= 0) { e.preventDefault() input.value = options()[active].textContent close() } else if (e.key === 'Escape') { close() } })
The keyboard handler.
Testing it in Chrome
The tests start the server, open the page in Chrome and type with real key events. A small helper, open, loads the page with a query string and waits 200 ms for it to settle. Three of the tests cover the data flow. The first loads the page with debouncing off and abort off, to reproduce the bug: typing pu sends two requests, and the slow reply for p wins, so the list shows nine cities for an input that says pu. The second turns abort on, and only the four pu matches remain. The third restores the 150 ms debounce and types pun with 60 ms between keys: the server sees one request.
const shown = (page) => page.locator('[role=option]').allTextContents() test('without abort, a slow old reply wins the list', async () => { const page = await open('wait=0&abort=0') await page.locator('#city').pressSequentially('pu', { delay: 60 }) await page.waitForTimeout(900) assert.deepEqual(app.log, ['p', 'pu']) assert.equal((await shown(page)).length, 9) }) test('with abort, only the newest query reaches the list', async () => { const page = await open('wait=0') await page.locator('#city').pressSequentially('pu', { delay: 60 }) await page.waitForTimeout(900) const names = ['Pune', 'Puri', 'Punalur', 'Puducherry'] assert.deepEqual(await shown(page), names) }) test('debounce turns three keystrokes into one request', async () => { const page = await open('') await page.locator('#city').pressSequentially('pun', { delay: 60 }) await page.waitForTimeout(900) assert.deepEqual(app.log, ['pun']) assert.deepEqual(await shown(page), ['Pune', 'Punalur']) })
The three data-flow tests.
Two more tests, in a second file, drive the keyboard. One presses Down twice and checks that aria-activedescendant points at the second option, that its aria-selected is true, and that Enter copies it into the input and closes the list. The other presses Up from the start and checks it lands on the last option, presses Down and checks the option did not change, then presses Escape and checks the attributes reset.
✔ without abort, a slow old reply wins the list (1646.554ms) ✔ with abort, only the newest query reaches the list (2037.7742ms) ✔ debounce turns three keystrokes into one request (1513.0177ms) ✔ arrow keys move the option and Enter picks it (1607.6209ms) ✔ Up picks the last, Down stops there, Escape closes (1339.9216ms) ℹ tests 5 ℹ pass 5 ℹ fail 0 ℹ duration_ms 9333.5925
Output (Node 24, node:test, run one file at a time)
All five pass. The files run one after another because both start a server on the same port, and --test-concurrency=1 stops node from running them together. The timings are lab numbers from this machine and vary, mostly Chrome starting for each test.
All chapters · Previous: How the Browser Loads and Renders a Page