feat(web): add browser.evaluateOn, toHaveCSS, and toHaveJSProperty
Â
SA
2d ago+3186+3186+0123456789012345678901234567890123456789-315-315-012345678901234567890123456789
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?)runsfn(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 withbrowser.evaluate.
The code runs once: a navigation while it runs fails the call withENGINE_FAILURE, exit code 3, asbrowser.evaluatealready does. Playwright reports the same case as a test failure.
A secure field isPOLICY_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. Amatches()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.evaluatedisposes its result handle too, so a longexpect.pollover 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)comparesgetComputedStyle(el).getPropertyValue(property)as the raw string, as Playwright does, so a custom--propertyworks.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 withnode:util'sisDeepStrictEqual.
A property that holds a promise or thenable is a value that is not JSON, so it never matches, and itsthenis never called.browser.evaluateandevaluateOnstill await a promise the test's own function returns.- The three
expect(browser)locator matchers (toHaveClassincluded) live inpackages/web/src/browser-expectation.tsand share one sampler: onecontext.withNode(..., { wait: false })per poll.
Zero matches isno nodeand one more poll. A target that is not this attempt's locator isINVALID_LOCATORon the first sample, whether or not it matches.
toHaveClassreadsclassfrom the node the resolve read, as main does. - Every
expect(browser)read, URL and title included, runs through the poll'sreads.read.
A value that never matches on a slow page now failsASSERTION_FAILED, where main'stoHaveClassandtoHaveTitlefailedACTION_FAILEDonce the deadline cut off a read. - Engine contract (
@e2e-dev/core/engine):EngineFixtureContext.withNode(api, locator, use, options?)runsuse(ref, operation, node)on the node a test's locator matches, withnodeas the resolve read it.
It sharesLocatorEngine.read's loop (withOne): zero matches poll, two areLOCATOR_AMBIGUOUSat once, a retryableNODE_STALEfromusere-resolves and runsuseagain.
A secure field isPOLICY_DENIEDbeforeuseruns.
wait: falseresolves once and fails zero matches asLOCATOR_NOT_FOUNDat once, for a matcher that polls on its own.pollCondition'sevaluatereceivesreads: PollReads, whose one method,read(call), bounds a read by the deadline and times it.compareTextis exported, so an engine can compare without collapsing whitespace.secureReadDenied(subject)is exported: thePOLICY_DENIEDerror for a read on a secure field.
Core'sdenySecureReadand 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/coreande2erise to>=0.25.0 <1: the published0.24.0has neitherwithNode,compareText, norsecureReadDenied.
The open release PR #1974 versions core and e2e as0.25.0(main has a breaking changeset), without these exports.
If0.25.0ships before this merges, the floor moves to0.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
withNodeis public engine contract, with a requiredapiargument so itsINVALID_LOCATORnames the public call, thewaitoption, and thenodeargument touse.
It is the generic "read a value from a locator" primitive the #1045 closing comment asked for.withNodedenies every secure field, for every caller.
SotoHaveCSS(password, 'border-top-color', ...)andtoHaveJSProperty(password, 'validity.valid', ...)arePOLICY_DENIED, and Playwright allows both.
The alternative is to hand over the node and let each value read deny, as core letsisEnabled(),boundingBox(), and the state matchers through.
This takes the fail-closed one: a future fixture built onwithNodecannot 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 anddocs/reference/engine.mdxsay so.- The denial covers the element the locator matches. This needs maintainer sign-off. A
toHaveJSPropertypath that walks elsewhere, such ascontrol.valueon a<label>orelements.pw.valueon a<form>, reads that element's value, andevaluateOncode can do the same.docs/reference/expect.mdxsays so.
A configured secret still prints as<secret:admin.password>. A value the app put in a password field itself prints as is, asbrowser.evaluatealready allows.
The alternative is to refuse a path that passes through a secure field inPROPERTY_PATH_SOURCE. That covers the matcher but notevaluateOn,browser.evaluate, orouterHTML. secureReadDeniedis 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.
Itssubjectends 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), sincewithNode'susegets no label.pollCondition'sevaluategetsPollReads, a one-method interface, not theReadWindowclass, so the window's cut-off judgment stays internal. The name is open.- The slow-read fix changes main's
toHaveClassandtoHaveTitle. 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 waitingwithNode. The waiting shape could not tell a missing node from a hung page, and broke threetoHaveClassbehaviors 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
evaluateOncomes from #1294, which left the name open.
An overload such asbrowser.evaluate(locator, fn)is the obvious alternative. toHaveClassrefuses a target that is not an e2e locator, or one from another attempt, withINVALID_LOCATORat once. On main a string target threw an uncodedTypeError, and a{ count, getAttribute }look-alike passed.- A navigation caused by test code inside
evaluateOnisENGINE_FAILURE, exit code 3, the infrastructure class, asbrowser.evaluatealready reports it.
Playwright reports the same case as a test failure.
Moving both to a test-class code is a separate change. toHaveCSSreads as page code in the main world, so a page that overridesgetPropertyValuechanges what it reads.
Playwright reads in its utility world. The docs say so.- The secure check reads
element.matchesin the page's main world, as the tree reader's own check already does (contentScript: false). A page that replacesElement.prototype.matcheswith() => falsedefeats both, on main too. That gap is older than this PR and is tracked in #2010. evaluateOncheckselement.isConnectedin 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 failsLOCATOR_NOT_FOUND.
It fails closed. A check outside the page needs a Playwright API the engine does not have.toHaveJSPropertyreads a path through anullbefore the last key asundefined, so.notpasses. Playwright throws there.docs/reference/expect.mdxsays so.- The Playwright gaps left (no
{ timeout }onevaluateOn, nopseudoontoHaveCSS, noundefinedexpected value) are listed indocs/migrate/playwright.mdx. Cannot find context with specified idnow reads as a navigation race (packages/web/src/support.ts).
The matcher navigation test hit it in 2 of 10 runs under CPU load, fromlocator.elementHandlesinsoleElement. No test forces that race on demand.- Untested on purpose:
- The
browser.evaluateOnstep label.Locatorhas no public label to show. currentUrl's read budget.page.url()never reads the page, so ignoring the budget behaves the same.
- The
- Known nit, not fixed: an
evaluateOnwhose code never settles failsACTION_FAILED: operation timed out: locator(...), worded by core's shared locator-error translation, wherebrowser.evaluatenames its own timeout. - Not in this PR: an
expect(browser)matcher that times out prints no code frame pointing at the test's line.toHaveClassalready did not.
Verified
Ran it locally: yes
- Head
e9252ed2e, merged with main634d06047: rootpnpm buildandpnpm checkexit 0. Testbedevaluate-on.e2e.ts56/56 on the built CLI.@e2e-dev/webevaluation,browser-expectation,evaluate-on,evaluate, andhung-page78 passed.
Theownerrefactor (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 position | expected "static" to be "sticky" (first <nav> read) | sticky |
<aside> width in the iframe | expected 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), main0e9d58ec, the previous headd4e20d6b, and this branch:
| Call | main | d4e20d6b | this branch |
|---|---|---|---|
getAttribute('class') | POLICY_DENIED | POLICY_DENIED | POLICY_DENIED |
toHaveClass(password, 'x') | POLICY_DENIED | ASSERTION_FAILED, observed class "field" | POLICY_DENIED |
toHaveJSProperty(password, 'value', 'x') | not on main | ASSERTION_FAILED, the message shows the value | POLICY_DENIED |
evaluateOn(password, (el) => el.value) | not on main | returns the value | POLICY_DENIED |
toHaveClass(#real, 'real') on a page that replaces getAttribute | passes | fails, observed class "fake" | passes |
- Testbed, built CLI, a text field that turns into a password field holding
app-secret-0xBEEFin the microtask after the engine's first value read (afterwithNode's check, before the page code runs), 3 runs each:
| Call | previous head f70cbe9b | this branch |
|---|---|---|
evaluateOn(field, (el) => el.type + ':' + el.value) | returns password:app-secret-0xBEEF 3/3 | POLICY_DENIED, the code never runs |
toHaveJSProperty(field, 'value', 'app-secret-0xBEEF') | passes 3/3 | POLICY_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 withoutdispose(), 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-runtimetest catcheswithOnehandingusethe 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 eddf5775 | this branch | |
|---|---|---|
toHaveClass(#b, 'z') | ACTION_FAILED 10/10 | ASSERTION_FAILED 10/10 |
toHaveTitle('Other') | ACTION_FAILED 10/10 | ASSERTION_FAILED 10/10 |
- A function that bumps a
sessionStoragecounter and reloads the page failsENGINE_FAILURE, and the counter reads1(testbed testfails, and never runs the function again, when the page navigates while it runs). npm installof this branch's packed@e2e-dev/webbeside the publishede2e@0.24.0and@e2e-dev/core@0.24.0stops withERESOLVE ... peer @e2e-dev/core@">=0.25.0 <1"(run on82e932df, the dependency set is unchanged since). The published0.24.0engine entry has none ofcompareText,withNode, orsecureReadDenied.browser.evaluate, 50 calls: the new integration testreleases the result handle of every evaluationcounts 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): withpackages/core/srcandpackages/web/srcreverted to the merge base, 51 fail, 2 are skipped, and 3 pass. The 3 pin main'stoHaveClassbehavior across the rewrite (a page that hangs before the first read, a page that replacesgetAttribute, 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-runevaluateOn, the matcher re-read after a reload, theisConnectedcheck, the slow-read assertion (read window left unfed), the late negation (a waiting sampler), and the timer-driventoHaveTitleandtoHaveURLunit test. - Head
fb4ede70, merged with main1b007d4d:evaluate-on.e2e.ts49/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 failedACTION_FAILED.
Full testbed suite 642 passed and 3 skipped,@e2e-dev/web883 passed and 1 skipped, e2e unit 4213 passed and 2 skipped on the tree of29765c0d. 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 of39ab6297):pnpm checkexit 0. - Head
39ab6297, merged with main3e7d19de:pnpm checkexit 0. Testbedevaluate-on.e2e.ts49/49 on the built CLI.@e2e-dev/webunit plus integrationevaluateandevaluate-on421 passed.
On82e932df:@e2e-dev/webunit plus integrationevaluate,evaluate-on, andhung-page425 passed. e2escripted-reads,scripted-matchers,web-platform, andmcp-run-code, which assert the refusal message, 68 passed. e2efixture-runtime,expect-async-value,expect-async-attributes,engine-guards, andengine-protocol133 passed.
🤖 Generated with Claude Code