Playwright Data Correctness Testing: Don't Test the UI, Test the Numbers — Turning a Live Dashboard into a Structured Snapshot You Can Reconcile

🇨🇳 中文版

In this Playwright suite, my proudest design is a test case that is "designed to always fail"

In a data test suite, the single most important test case should be one that always fails.

This is not a figure of speech. In my alva-e2e repository, tests/comps.spec.ts has a test case called EV and Market Cap should have real values (currently all $0.0, a known defect) (translated from the Chinese test name), and it goes red on every full run. The most recent complete run was 106 passed / 1 failed, and that 1 failed is it. I think it going red is precisely what shows the suite is working — because it guards a real, unfixed live data defect, and the moment it turns green, there are only two possibilities: the defect was fixed, or the extraction layer broke.

Most people write Playwright to "simulate a user clicking buttons and assert elements appear." What I wrote this time is something else: pulling the numbers off the page and doing accounting reconciliation. Below I'll explain in the order I actually hit the pitfalls: the five default practices of mainstream E2E, where each of them fails under the goal of "data correctness," and what I ultimately replaced them with. There are three hooks planted up front — $0.0, 106 passed / 1 failed, and that sentinel script check-patrol.mjs which is not in tests/.

1. First, the mainstream: why "click buttons + assert elements appear" is not enough in data scenarios

A comparative analysis should first give the mainstream its due. The goal of UI E2E is "can the user complete the flow," so assertions like expect(locator).toBeVisible() and toHaveText() are entirely correct — they answer "is the button there, does clicking it do anything, is the navigation right." In scenarios like forms, checkout, and login, this is exactly what should be done, and there's nothing to criticize.

The failure boundary appears when the object under test changes in nature. If the object under test is a financial data dashboard, then "elements are visible" and "data is correct" are two almost unrelated things.

My target this time was an AMD Deep-Dive playbook page on alva.ai. In its comparable companies table, every company — INTC, NVDA, QCOM, TSM, ARM, even the two aggregate rows Average / Median — has its EV and Market cap rendered as $0.0, all 11 rows of the entire column without exception.

From the UI level, it "renders normally": the table structure is complete, columns are aligned, the number positions have content, and there are no errors. Any toBeVisible() would pass one hundred percent. From the data level, this is a disaster. I logged this defect as D-1 in §2 of docs/PART2-data-correctness.md, and it's also explicitly written in the Known limitations of README.md:

This suite caught one for real: every company's EV and Market cap in the comps table renders as $0.0

This is where the mainstream approach fails: between asserting "something is displayed" and asserting "what is displayed is correct" lies an entire data semantics layer. The former is a DOM problem, the latter is an accounting problem. My whole setup exists to cross that layer.

2. Starting with the mainstream approach, I ran into progressive rendering

I initially wrote it following the standard tutorial: page.goto(), then waitUntil: 'networkidle', waiting for the page to "quiet down" before asserting. After two days I found this path didn't work, and the reasons are all recorded in the source code comments.

The first pitfall is the iframe. The main content is not in the main document but in an <iframe title="Dashboard">; the main document doesn't even have an h1, and the only semantic heading is inside the iframe. So helpers/common.ts has a dedicated dashboard(page) that returns page.frameLocator('iframe[title="Dashboard"]'), and a companyHeading(page) that goes into the iframe to find that Advanced Micro Devices heading. This is just troublesome, not hard.

The real difficulty is the second pitfall: this iframe navigates/redirects multiple times during cold start. SSR first places an about:blank placeholder frame, then commits to the real production API content frame, and there may be a boot reload in between. If you "grab a Frame reference and hold it long-term," the placeholder frame will DETACH when the real navigation commits, and the waitForFunction / evaluate bound to it will immediately throw Frame was detached, taking down an entire group of @data assertions at once.

So I gave up holding the frame and instead re-resolve the currently live frame every time it's used. liveDashboardFrame(page) in helpers/extract.ts is exactly this idea — match by name (playbook-content) or a known dashboard domain, require the URL to be committed, not about:blank, and not detached, returning only the real content frame "at this moment"; return null if not ready. The companion dashboardFrame(page) is the blocking version, waiting up to 30 seconds until the real frame appears.

The third pitfall is the most critical: networkidle is a fake "quiet" for this page. The dashboard's data is progressively filled in: the skeleton (—/Loading…) renders first, and the quotes and financial numbers are only inserted into the DOM after more than 20 APIs return serially. When the network layer goes quiet, the numbers may still be —. This is why I never trusted networkidle afterward — it tests the network, not the data.

So I switched to a semantic readiness criterion, waitForDataReady. It does waitForFunction inside the frame, requiring three signals to hold simultaneously before considering it ready:

  • At least one KPI value is a real price (matching /^\$\d/)
  • The comparable companies table has at least 5 tickers (.comps-grid .cg-tk)
  • The financial table has at least 15 data rows (.table-row.table-body-row)

Later a fourth signal was added, forced out by a flaky test. The valuation multiples' sub (the "TTM P/E" style basis note) is one of the last fields the page fills in: in early snapshots kpi-value is already a price, but kpi-sub is still an empty placeholder. Without waiting for it, the "with TTM basis note" assertion in valuation.spec would intermittently go red falsely — that's the flaky recorded in README.md, later located and fixed. So now valuationReady is also part of the readiness condition: the value of the P/E, P/S, and EV / EBITDA cells is already a number and the sub contains TTM.

Incidentally, waitForDataReady is wrapped in a loop with a timeout budget, specifically to handle the frame detaching mid-wait — re-resolve the latest frame and retry. This outer loop looks clumsy, but it downgrades "frame reload" from a fatal error to a retryable event.

3. From "assert while clicking" to "one snapshot, reconcile everything"

The mainstream E2E approach is to assert while operating, clicking a few times and asserting a few times within one test case. This pattern has a hard flaw in data validation: every assertion requires reloading the page once. This page takes 20–40 seconds per load, and with a dozen-plus test cases each loading it once, the suite becomes too slow to be usable.

More critically, I discovered something counterintuitive at the time: this dashboard is a single-page long document. The 7 tabs merely toggle the visibility of sections; all tabs' data is already in the DOM after the first load. I measured it: the textContent snapshot before and after switching tabs is completely identical. The comment at the top of extract.ts states these two premises plainly:

Therefore textContent extraction is used uniformly here rather than waiting for visibility — data validation is unaffected by which tab is currently active, and it also avoids reloading the slow page once for each test case.

A large amount of content inside the iframe is in an "invisible" state (innerText can only get ~9k characters of the currently active section, while textContent can get all ~40k characters).

The second point is especially important: with innerText you can only get about 9k characters of the currently active section, while with textContent you can get all ~40k characters. Data validation must use querySelectorAll + textContent, not innerText — this is not a performance optimization, it's a correctness issue.

So the architecture split into two layers. The lower layer extractDashboard(page) does a single DOM traversal, extracting the entire dashboard into a structured DashboardData snapshot: kpis, tables, comps (including compsFyLabels), analyst, risks, revenueMixPct, timestamps, allText, dataCells. The upper layer loadDashboard(browser) opens the page, waits for readiness, and grabs a snapshot, sharing that single load within one describe.

All assertions are done on the Node side against this snapshot, no longer touching the browser. This is what I mean by "structured snapshot" in the title — it's not an HTML snapshot, it's translating the dashboard into objects that can be reconciled against each other.

helpers/parse.ts is the companion to this layer: restoring display strings into comparable numbers. Amounts $750.1B / $625.0M / $457.06 / $0.0 go through parseMoney, percentages -17.25% / +104.53% / -21.83% from high go through parsePercent, multiples 116.6× / NM go through parseMultiple, and dates and counts each have their own. There's a principle I insist on here, written at the top of the file:

All functions return null to mean "cannot parse" or "empty value," and never return 0 or NaN — 0 is a legitimate value with business meaning, and cannot be used to represent missing.

isEmptyValue treats —, –, NM as empty, but explicitly excludes $0.0 — $0.0 is not an empty value, it's a real (suspicious) number. This distinction is exactly the premise that makes the D-1 test case valid.

The reconciliation a snapshot can do is far richer than point-by-point assertions. For example, relativeDiff(a, b) is used to assert "the same metric from two sources should be close": the revenue back-derived from the comparable companies table and the same-basis number in the financial table should fall within a relative error. This kind of "internal self-consistency" check is something a single-side assertion can never discover.

4. "Should CI go red": dirty-value scanning and its false-positive boundary

With the snapshot, the most straightforward thing I wanted to do was: scan everything and see whether the page renders things like NaN or undefined directly. Once such text appears, it means the frontend is spitting undefined values straight onto the interface, which is a failure with clear business impact.

DIRTY_PATTERNS in parse.ts lists NaN, undefined, Infinity, [object Object], null, $NaN, NaN%, NaN×, and findDirtyValues(texts) handles the filtering.

Here I hit a typical pitfall: you can't scan the entire text. I initially matched directly against allText, and the null pattern hit English words in the body text — for example, annulment contains the substring null. Scanning the whole text produces false positives. So DashboardData keeps a separate field dataCells, with a comment stating it clearly: scan only data cells, not the entire text. The trade-off for this field was bought with that one false positive.

The same "should CI go red" question also shows up in the D-1 test case. Putting an always-red test case into CI is intuitively unacceptable — all-green CI is the bottom line for many teams. But I think about it the other way: the nature of this test case is not a "new bug detector," it's a "known defect tracker." It only asserts EV / market cap ≠ 0, and it turns green the moment the defect is fixed; it cannot catch finer problems like "EV was computed as a different wrong number," which would require value-level validation beyond the current scope. In README.md I classified it under Known limitations, which is exactly this meaning.

The mainstream approach would require "marking known defects with skip." I refuse: skipped test cases are ones nobody comes back to look at, whereas keeping a red test case reminds you "this defect is still here" on every run.

5. Building a sentinel script that is not in tests/

Having one red test case brings a new problem: when the suite has a test case that "is supposed to be red," how do you know it hasn't incidentally made others red too? The 1 in 106 passed / 1 failed is correct, but could the 106 include some that should have failed but "falsely went green" because the extraction layer degraded?

This is the origin of check-patrol.mjs. It's not in tests/, it's not a Playwright spec, but an independent script. Its job is not to run tests, but to verify that the shape of this run's numbers is correct: how many passed, how many failed, and whether the failure is the one allowed to fail. 106 passed / 1 failed is a decidable expected shape, not a vague "mostly green."

At this point I've collected all the hooks from earlier: $0.0 is the target, check-patrol.mjs is the sentinel guarding the target, and 106 passed / 1 failed is the shape the sentinel approves. Only when the three interlock does "one always-red test case" turn from an engineering taboo into an operable design.

6. The five default practices I replaced, and their costs

Looking back, I did the opposite of all five default practices of mainstream Playwright this time. Each one can be traced to a reason in the source code:

Mainstream default practice My practice Reason for doing the opposite
Assert element visibility / text matching Extract data into structured snapshots, reconcile on the Node side Element visibility is almost unrelated to data correctness; $0.0 would pass visibility assertions 100%
Use networkidle to wait for the page to quiet down waitForDataReady waits for three/four semantic signals Data is progressively filled in; when the network is silent the numbers may still be —
Hold a Frame / Locator for long-term use Re-resolve the live frame with liveDashboardFrame each time The iframe navigates multiple times during cold start, and the placeholder frame detaches
Use innerText to read content querySelectorAll + textContent innerText of invisible sections only gets ~9k, textContent gets ~40k
CI must be all green / skip known defects Keep one "designed to fail" test case, with a sentinel script to verify the shape A defect tracker must stay red to have presence; the shape is decided by check-patrol.mjs

But I have to be honest about the costs, which is also what a comparative analysis should include. I listed four in the Known limitations of README.md, none of them perfunctory:

First, there is only one target page and one point in time. This is a snapshot of a single ticker, the page refreshes roughly every 4 hours, and structural drift cannot be ruled out.

Second, all cross-validation is "internal self-consistency," not "comparison against external truth." Back-deriving revenue from Market cap ÷ P/S, cross-checking the comps table and financial table on the same basis — all self-verified within the page. If the backend is simultaneously wrong across all data sources (e.g., exchange rates, unit basis), the suite would be all green but still wrong. To truly guard against this, you'd need to introduce external ground truth (SEC / market data APIs) for three-way comparison, which this version doesn't do.

Third, rate limiting makes the run itself unstable. The site limits high-frequency access; after a dozen-plus consecutive runs the API intermittently returns empty data, and pnpm test occasionally fails simply because no data was loaded, requiring --workers=1 serial retries. That is, CI must tolerate flakiness, or add warm-up / backoff, otherwise it produces false reds.

Fourth, the authenticated state is deliberately out of scope. Registration, creating automations, alert configuration and push are all excluded, because they require a real account, and only public pages can be patrolled unattended. That part has exploration records in docs/PART1-onboarding.md, but two things can't be automated: the automation itself is an asynchronous LLM workflow (taking several minutes), so you can only assert "the instruction entered the conversation," not "the final generated spec is correct"; real alert triggering requires the market to actually cross the configured threshold, an uncontrollable wait that can only be manually walked through.

Conclusion

The sharpest thing about this setup is not "I wrote a Playwright test suite," but that it moves E2E's main battlefield from UI behavior to data correctness. The mainstream approach isn't wrong; it just answers a different question. Once your goal is "are the numbers on the page correct," you'll find that toBeVisible doesn't help, networkidle lies to you, innerText misses data, and all-green CI instead becomes a metric that needs redefining.

And that always-failing test case happens to be the distillation of all of this: its red is one of the only honest signals in this suite.

Source code navigation

Repository: https://github.com/erishen/alva-e2e

  • README.md — suite positioning, artifact list, Known limitations (including the D-1 $0.0 defect and the 106 passed / 1 failed run result)
  • docs/PART2-data-correctness.md — data correctness report: defect log (D-1 confirmed + D-2~D-6 guards), coverage matrix, run evidence and fix history
  • docs/PART1-onboarding.md — login journey exploration report (F-1~F-9) and logged-in state test evidence
  • tests/helpers/common.ts — gotoPlaybook / dashboard / companyHeading / waitForDataReady / loadDashboard, readiness criteria and frame retry logic are all here
  • tests/helpers/extract.ts — liveDashboardFrame / dashboardFrame / extractDashboard and all DashboardData type definitions, the snapshot layer implementation
  • tests/helpers/parse.ts — parseMoney / parsePercent / parseMultiple / parseCount / parseIsoDate / parseDisplayDate / daysBetween / relativeDiff / findDirtyValues, including DIRTY_PATTERNS and isEmptyValue
  • tests/comps.spec.ts — contains that EV and Market Cap should have real values test case designed to always fail
  • evidence/ — automatically captured defect screenshots (the $0.0 column highlighted)
  • check-patrol.mjs — the sentinel script that verifies the shape of a single run (not inside tests/)

Why is it said that the $0.0 defect cannot be caught with visibility assertions?

Because at the UI level it "renders normally" — the table structure is complete, columns are aligned, the number positions have content, and any toBeVisible() would pass; it's wrong at the data semantics layer, and you need to parse out the values and then judge to discover that all 11 rows of the EV and Market cap column are $0.0.

Why not just use networkidle to wait for the page to finish loading?

The dashboard is progressively filled in: the skeleton renders first, and the numbers are only inserted into the DOM after more than 20 APIs return serially, so when the network is silent the numbers may still be —; so waitForDataReady is used instead, requiring at least one KPI to be a real price, the comps table to have at least 5 tickers, the financial table to have at least 15 rows, and the valuation KPI's value to be a number with sub containing TTM — all four signals holding simultaneously.

Why can't you hold a reference to the iframe's Frame?

This iframe navigates/redirects multiple times during cold start; SSR first places an about:blank placeholder frame then commits to the real content frame, and the placeholder frame DETACHes when the navigation commits, so the waitForFunction / evaluate bound to it immediately throws Frame was detached; therefore you must re-resolve the currently live frame with liveDashboardFrame each time, and retry if it detaches mid-way.

Why use textContent instead of innerText?

A large amount of content inside the iframe is invisible; innerText can only get about 9k characters of the currently active section, while textContent can get all ~40k characters; data validation is unaffected by which tab is currently active and must also cover all sections, so querySelectorAll + textContent must be used.

Why must dirty-value scanning be limited to dataCells rather than scanning the whole site's text?

Scanning the entire text produces false positives, for example the null pattern hits English words in the body text (such as annulment); so DashboardData has a separate dataCells field, scanning only data cells.

What is check-patrol.mjs for?

It's an independent sentinel script, not a Playwright spec in tests/; its job is not to run tests but to verify the shape of a run — how many passed, how many failed, and whether the failure is that D-1 $0.0 test case allowed to fail — thereby preventing other test cases from falsely going green under the premise that "one is supposed to be red anyway."

Comments (0)

    Comments require approval before appearing. Markdown supported.

    ← Back to list
    erishen

    Written by

    erishen

    Senior full-stack engineer focused on AI application engineering & delivery. Author of lume, lume-core and open-source AI engineering tooling.

    ⭐

    Enjoy this article?

    erishen/alva-e2e

    Star on GitHub