feat(web): add browser.evaluateOn, toHaveCSS, and toHaveJSProperty

SA
2d ago
+3186-315

Issue

Closes #1294.

Why

Reading a computed style or DOM property today means browser.evaluate with a CSS selector that finds the element a second time.
That selector ignores the locator's scope, strict single match, and frame, so it can read a different element from the one the test meant.

What changes

  • browser.evaluateOn(locator, fn, arg?) runs fn(element, arg) in the page on the one element the locator matches.
    It resolves with the locator's scope, strictness, and frame, and waits for the match like a locator read.
    The argument and the result stay JSON, as with browser.evaluate.
    The code runs once: a navigation while it runs fails the call with ENGINE_FAILURE, exit code 3, as browser.evaluate already does. Playwright reports the same case as a test failure.
    A secure field is POLICY_DENIED, as the locator getters deny it.
    The page-side boundary checks the element again in the same page task, before the test's code runs, so a node that turns into a password field after the locate is refused too. A matches() that throws or answers no boolean counts as secure.
    It disposes the Playwright handle of every evaluation, so a long matcher poll does not pile up handle objects.
  • browser.evaluate disposes its result handle too, so a long expect.poll over it no longer grows the runner's memory with every read until the page closes (.changeset/web-evaluate-dispose.md).
  • expect(browser).toHaveCSS(locator, property, expected) compares getComputedStyle(el).getPropertyValue(property) as the raw string, as Playwright does, so a custom --property works.
  • expect(browser).toHaveJSProperty(locator, path, expected) walks a dotted path the way Playwright 1.65.1 does, with one difference listed below, and compares the values as JSON with node:util's isDeepStrictEqual.
    A property that holds a promise or thenable is a value that is not JSON, so it never matches, and its then is never called. browser.evaluate and evaluateOn still await a promise the test's own function returns.
  • The three expect(browser) locator matchers (toHaveClass included) live in packages/web/src/browser-expectation.ts and share one sampler: one context.withNode(..., { wait: false }) per poll.
    Zero matches is no node and one more poll. A target that is not this attempt's locator is INVALID_LOCATOR on the first sample, whether or not it matches.
    toHaveClass reads class from the node the resolve read, as main does.
  • Every expect(browser) read, URL and title included, runs through the poll's reads.read.
    A value that never matches on a slow page now fails ASSERTION_FAILED, where main's toHaveClass and toHaveTitle failed ACTION_FAILED once the deadline cut off a read.
  • Engine contract (@e2e-dev/core/engine):
    • EngineFixtureContext.withNode(api, locator, use, options?) runs use(ref, operation, node) on the node a test's locator matches, with node as the resolve read it.
      It shares LocatorEngine.read's loop (withOne): zero matches poll, two are LOCATOR_AMBIGUOUS at once, a retryable NODE_STALE from use re-resolves and runs use again.
      A secure field is POLICY_DENIED before use runs.
      wait: false resolves once and fails zero matches as LOCATOR_NOT_FOUND at once, for a matcher that polls on its own.
    • pollCondition's evaluate receives reads: PollReads, whose one method, read(call), bounds a read by the deadline and times it.
    • compareText is exported, so an engine can compare without collapsing whitespace.
    • secureReadDenied(subject) is exported: the POLICY_DENIED error for a read on a secure field.
      Core's denySecureRead and the web engine's page-side refusal both throw it, so the two messages cannot drift apart.
  • @e2e-dev/web's peers on @e2e-dev/core and e2e rise to >=0.25.0 <1: the published 0.24.0 has neither withNode, compareText, nor secureReadDenied.
    The open release PR #1974 versions core and e2e as 0.25.0 (main has a breaking changeset), without these exports.
    If 0.25.0 ships before this merges, the floor moves to 0.25.1.
const main = screen.getByRole('navigation', { name: 'Main' });
expect(await browser.evaluateOn(main, (el) => getComputedStyle(el).position)).toBe('sticky');
await expect(browser).toHaveCSS(main, 'position', 'sticky');

const aside = browser.frameLocator('iframe').locator('aside');
await expect(browser).toHaveJSProperty(aside, 'offsetWidth', 240);
flowchart LR
  E[browser.evaluateOn] -->|wait for the match| W[context.withNode]
  M[toHaveClass / toHaveCSS / toHaveJSProperty poll] -->|"reads.read, wait: false"| W
  W --> R[LocatorEngine.withOne: resolve, re-resolve on NODE_STALE]
  R --> D{secure field?}
  D -- yes --> P[POLICY_DENIED]
  D -- no --> U["use(ref, operation, node)"]
  U -->|toHaveClass| N[node.attributes.class]
  U -->|evaluateOn, toHaveCSS, toHaveJSProperty| S[PlaywrightSurface.evaluateOn: element first, JSON boundary]

Decisions a reviewer may want to revisit

  • withNode is public engine contract, with a required api argument so its INVALID_LOCATOR names the public call, the wait option, and the node argument to use.
    It is the generic "read a value from a locator" primitive the #1045 closing comment asked for.
  • withNode denies every secure field, for every caller.
    So toHaveCSS(password, 'border-top-color', ...) and toHaveJSProperty(password, 'validity.valid', ...) are POLICY_DENIED, and Playwright allows both.
    The alternative is to hand over the node and let each value read deny, as core lets isEnabled(), boundingBox(), and the state matchers through.
    This takes the fail-closed one: a future fixture built on withNode cannot forget the check for the node it is handed.
    Page code that runs on the element later still checks again in the page, since the page can change the node in between. withNode's JSDoc and docs/reference/engine.mdx say so.
  • The denial covers the element the locator matches. This needs maintainer sign-off. A toHaveJSProperty path that walks elsewhere, such as control.value on a <label> or elements.pw.value on a <form>, reads that element's value, and evaluateOn code can do the same. docs/reference/expect.mdx says so.
    A configured secret still prints as <secret:admin.password>. A value the app put in a password field itself prints as is, as browser.evaluate already allows.
    The alternative is to refuse a path that passes through a secure field in PROPERTY_PATH_SOURCE. That covers the matcher but not evaluateOn, browser.evaluate, or outerHTML.
  • secureReadDenied is new public engine contract. It settles a review nit about the page-side refusal copying core's wording. An engine imports only from @e2e-dev/core/engine, so the alternative is to keep the copied string in the web engine.
    Its subject ends the message: core passes the locator label, and the page-side refusal passes its reason (the element is one now but was not when located, or its type cannot be checked), since withNode's use gets no label.
  • pollCondition's evaluate gets PollReads, a one-method interface, not the ReadWindow class, so the window's cut-off judgment stays internal. The name is open.
  • The slow-read fix changes main's toHaveClass and toHaveTitle. It ships here because the new matchers share the poll, and it has its own changeset (.changeset/web-matcher-slow-read.md), so it could split out.
  • Matchers sample with wait: false, not a waiting withNode. The waiting shape could not tell a missing node from a hung page, and broke three toHaveClass behaviors main has (a node removed after one read, a late negation, a page that hangs before the first read). Each is now a testbed test.
  • The name evaluateOn comes from #1294, which left the name open.
    An overload such as browser.evaluate(locator, fn) is the obvious alternative.
  • toHaveClass refuses a target that is not an e2e locator, or one from another attempt, with INVALID_LOCATOR at once. On main a string target threw an uncoded TypeError, and a { count, getAttribute } look-alike passed.
  • A navigation caused by test code inside evaluateOn is ENGINE_FAILURE, exit code 3, the infrastructure class, as browser.evaluate already reports it.
    Playwright reports the same case as a test failure.
    Moving both to a test-class code is a separate change.
  • toHaveCSS reads as page code in the main world, so a page that overrides getPropertyValue changes what it reads.
    Playwright reads in its utility world. The docs say so.
  • The secure check reads element.matches in the page's main world, as the tree reader's own check already does (contentScript: false). A page that replaces Element.prototype.matches with () => false defeats both, on main too. That gap is older than this PR and is tracked in #2010.
  • evaluateOn checks element.isConnected in the page to tell a detached node from a live one.
    A page that overrides that getter makes every read look stale, so the call retries until its timeout and fails LOCATOR_NOT_FOUND.
    It fails closed. A check outside the page needs a Playwright API the engine does not have.
  • toHaveJSProperty reads a path through a null before the last key as undefined, so .not passes. Playwright throws there. docs/reference/expect.mdx says so.
  • The Playwright gaps left (no { timeout } on evaluateOn, no pseudo on toHaveCSS, no undefined expected value) are listed in docs/migrate/playwright.mdx.
  • Cannot find context with specified id now reads as a navigation race (packages/web/src/support.ts).
    The matcher navigation test hit it in 2 of 10 runs under CPU load, from locator.elementHandles in soleElement. No test forces that race on demand.
  • Untested on purpose:
    • The browser.evaluateOn step label. Locator has no public label to show.
    • currentUrl's read budget. page.url() never reads the page, so ignoring the budget behaves the same.
  • Known nit, not fixed: an evaluateOn whose code never settles fails ACTION_FAILED: operation timed out: locator(...), worded by core's shared locator-error translation, where browser.evaluate names its own timeout.
  • Not in this PR: an expect(browser) matcher that times out prints no code frame pointing at the test's line. toHaveClass already did not.

Verified

Ran it locally: yes

  • Head e9252ed2e, merged with main 634d06047: root pnpm build and pnpm check exit 0. Testbed evaluate-on.e2e.ts 56/56 on the built CLI. @e2e-dev/web evaluation, browser-expectation, evaluate-on, evaluate, and hung-page 78 passed.
    The owner refactor (8c4d375f7) is caught both ways: awaiting engine reads fails 5 testbed promise cases, and treating an engine read as unrepeatable fails the matcher reload test.
  • Testbed, built CLI, the issue's page (two <nav> elements, one sticky, and an iframe <aside style="width: 240px">):
main (browser.evaluate + querySelector)this branch (browser.evaluateOn)
Main nav positionexpected "static" to be "sticky" (first <nav> read)sticky
<aside> width in the iframeexpected null to be 240 (selector cannot reach the frame)240
  • Testbed, built CLI, a password field holding a value the app set (app-generated-0xBEEF), main 0e9d58ec, the previous head d4e20d6b, and this branch:
Callmaind4e20d6bthis branch
getAttribute('class')POLICY_DENIEDPOLICY_DENIEDPOLICY_DENIED
toHaveClass(password, 'x')POLICY_DENIEDASSERTION_FAILED, observed class "field"POLICY_DENIED
toHaveJSProperty(password, 'value', 'x')not on mainASSERTION_FAILED, the message shows the valuePOLICY_DENIED
evaluateOn(password, (el) => el.value)not on mainreturns the valuePOLICY_DENIED
toHaveClass(#real, 'real') on a page that replaces getAttributepassesfails, observed class "fake"passes
  • Testbed, built CLI, a text field that turns into a password field holding app-secret-0xBEEF in the microtask after the engine's first value read (after withNode's check, before the page code runs), 3 runs each:
Callprevious head f70cbe9bthis branch
evaluateOn(field, (el) => el.type + ':' + el.value)returns password:app-secret-0xBEEF 3/3POLICY_DENIED, the code never runs
toHaveJSProperty(field, 'value', 'app-secret-0xBEEF')passes 3/3POLICY_DENIED

The testbed test refuse a node that becomes a secure field after the locate, before its page code runs fails on f70cbe9b and passes 5/5 here.

  • Playwright 1.65.1, 200 elementHandle.evaluateHandle(...).jsonValue() calls: the client connection keeps 200 more objects without dispose(), and 0 more with it.
    The new integration test catches the result-handle dispose and the element-handle dispose removed (10/10 each), and the stale-path dispose removed (5/5).
  • The new fixture-runtime test catches withOne handing use the bare remaining time instead of the read window's slack 10/10, and passes 10/10 idle, pinned to one CPU, and under 8 busy loops.
  • Testbed, built CLI, a value that never matches on a page that blocks its main thread 300 ms of every 320 ms, { timeout: 1500 }, 10 runs each:
main eddf5775this branch
toHaveClass(#b, 'z')ACTION_FAILED 10/10ASSERTION_FAILED 10/10
toHaveTitle('Other')ACTION_FAILED 10/10ASSERTION_FAILED 10/10
  • A function that bumps a sessionStorage counter and reloads the page fails ENGINE_FAILURE, and the counter reads 1 (testbed test fails, and never runs the function again, when the page navigates while it runs).
  • npm install of this branch's packed @e2e-dev/web beside the published e2e@0.24.0 and @e2e-dev/core@0.24.0 stops with ERESOLVE ... peer @e2e-dev/core@">=0.25.0 <1" (run on 82e932df, the dependency set is unchanged since). The published 0.24.0 engine entry has none of compareText, withNode, or secureReadDenied.
  • browser.evaluate, 50 calls: the new integration test releases the result handle of every evaluation counts 50 leaked objects with the dispose removed and passes with it.
    The handle-count helper both dispose tests share first checks that one undisposed handle adds one object, so a Playwright that stops tracking handles there fails the tests instead of passing them.
  • apps/testbed/tests/evaluate-on.e2e.ts (56 tests): with packages/core/src and packages/web/src reverted to the merge base, 51 fail, 2 are skipped, and 3 pass. The 3 pin main's toHaveClass behavior across the rewrite (a page that hangs before the first read, a page that replaces getAttribute, a whitespace-padded class), and each fails under its own mutation.
  • Each timing test catches its mutation 10/10 idle, under 8 busy CPU loops, and pinned to one CPU (taskset -c 0), and passes 10/10 in each mode unmutated: the navigation that must not re-run evaluateOn, the matcher re-read after a reload, the isConnected check, the slow-read assertion (read window left unfed), the late negation (a waiting sampler), and the timer-driven toHaveTitle and toHaveURL unit test.
  • Head fb4ede70, merged with main 1b007d4d: evaluate-on.e2e.ts 49/49 in 3 runs at a load average of 12.5 on 8 cores. Its 300 ms matcher timeouts are 1000 ms now, since at that load a 300 ms matcher read no sample and failed ACTION_FAILED.
    Full testbed suite 642 passed and 3 skipped, @e2e-dev/web 883 passed and 1 skipped, e2e unit 4213 passed and 2 skipped on the tree of 29765c0d. In that e2e unit run, secret-ledger.test.ts's wall-time case took 6.9 s against its 5 s limit under load. It passes 3/3 alone and this branch does not touch it.
  • Head ef0da552 (a docs example fix on top of 39ab6297): pnpm check exit 0.
  • Head 39ab6297, merged with main 3e7d19de: pnpm check exit 0. Testbed evaluate-on.e2e.ts 49/49 on the built CLI. @e2e-dev/web unit plus integration evaluate and evaluate-on 421 passed.
    On 82e932df: @e2e-dev/web unit plus integration evaluate, evaluate-on, and hung-page 425 passed. e2e scripted-reads, scripted-matchers, web-platform, and mcp-run-code, which assert the refusal message, 68 passed. e2e fixture-runtime, expect-async-value, expect-async-attributes, engine-guards, and engine-protocol 133 passed.

🤖 Generated with Claude Code