Repository navigation
feat(web): add browser.evaluateOn, toHaveCSS, and toHaveJSProperty - #1822
samanyudas wants to merge 80 commits into
Conversation
A fixture method that takes a test's Locator had no way to reach the node it names, so page code fell back to a second selector that ignores the locator's scope, strictness, and frame. EngineFixtureContext.withNode resolves the node the way a locator read does and hands its ref to the fixture; LocatorEngine.read now runs on the same loop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reading a computed style or DOM property meant a document.querySelector inside browser.evaluate, which can read another element than the locator names and cannot reach into a frame. browser.evaluateOn(locator, fn, arg) runs the page function on the one element the locator matches, through withNode, and keeps browser.evaluate's boundary byte for byte. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests polled browser.evaluate by hand to wait for a style or a property. expect(browser).toHaveCSS and toHaveJSProperty sample through evaluateOn within the assertion's deadline, so a node that never arrives fails as ASSERTION_FAILED at the assertion timeout and an ambiguous locator fails at once, as toHaveClass does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reference pages, the browser guide, the e2e skill, and the Playwright and Cypress migration guides still sent readers to a selector inside browser.evaluate. They now name the locator-based read and the two matchers, and the changeset announces them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rtion timeout A sample read ran in a read window that lets its last read outlast the wait, so a matcher could pass after its timeout. Each sample now counts matches first, as toHaveClass does, and is capped at the poll's deadline; a read the deadline cuts off keeps the last observation that finished. toHaveJSProperty read every INVALID_ARGUMENT as a value that is not JSON, which swallowed a route handler failure the surface had latched. The evaluation boundary now marks its own refusal and the matcher catches only that. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A sample the assertion deadline cut off returned an undecided result, which reset the hold a negated matcher had built, so `.not.toHaveJSProperty` failed when its last read stalled past the timeout. The poll now counts the last finished read again, as pollReads does for its own cut-off reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two rounds of hand-rolled cut-off rules let a negation pass on a page that stopped answering. Each sample now counts first, reads on the action timeout inside the poll's deadline, and rethrows a timeout, so core's poll judges it the way it judges a class read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ntity The matcher recognized the boundary's own refusal by a WeakSet of error objects, which any wrapping or rethrow could lose. The surface now returns the decoded result, so the matcher reads `invalid` as a value and browser.evaluateOn alone turns it into INVALID_ARGUMENT. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…'s page call The page function got one argument or two depending on whether `arg` was given. A default parameter applies to an undefined argument either way, so the extra call shape only added a branch. browser.evaluate keeps its own two. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A non-locator target failed with "this call requires an e2e locator", which names no API. withNode now takes the public call's name first, so a fixture cannot forget it, and the web fixture passes browser.evaluateOn and the qualified matcher names. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A label locator resolves to a pinned element handle, a path no test took, and the INVALID_ARGUMENT refusals of a bad path, an undefined or non-JSON expected value, and a non-JSON argument had no test either. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…UATE_FAILED The classifier probed the element's frame, but ownerFrame runs page script too, so on such a page it failed first and the error stayed ENGINE_FAILURE. The page now stands in for the frame. The new surface tests also pin the stale ref a second match makes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mutations that retried a stale ref past the deadline, retried a stale node that is not retryable, ignored options.timeout, or skipped the locator translation all survived the existing tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ual's own-key check getPropertyValue always returns a string, so the typeof branch never ran. Object.hasOwn in jsonEqual is not redundant: without it an own __proto__ key equals any other key whose value is an empty object, so a test pins it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The new signatures, matcher labels, and page-code JSDoc ran well past the line length the rest of the change keeps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reference interface blocks now mirror the wrapped signatures, the INVALID_LOCATOR cell says the message names browser.evaluateOn, and the changeset keeps one user-facing sentence without engine internals. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…OUND A fresh-context review found that handing use the action timeout, or dropping evaluateOn's timeout: false, survived every test. These two cases fail on either mutation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ral values Counting a missing node as a mismatch, leaving a non-JSON value undecided, or comparing expected with === all survived the suite. Each of these testbed cases fails on one of them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A result that is not JSON from browser.evaluateOn said "evaluate result ...", which points the reader at the wrong call. browser.evaluate keeps its message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
element.ownerFrame() throws on a page that broke Map, so the fallback always probed the top-level page anyway. Probe it directly, and limit the docs to the top-level case, which is the one it detects. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The walk stepped through any value that was not null, so value.0.length on an input read 1 where Playwright reads undefined. Every step but the last now needs an object that has the next key, as Playwright 1.65.1's to.have.property checks, and null stops the walk too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The branch added lines past the repository's 100 character width, a loose list in the withNode docs, and the same JSDoc in two places. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The ExpectationDeps.evaluateOn signature, requireName's throw, and the matcher read timeout ran past the repository's 100 character line limit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rough one helper The three locator matchers each counted matches, bounded the read by the poll's deadline, and read LOCATOR_NOT_FOUND as no node; sampleNode now does that once, and each matcher keeps only its own read and observation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…LOCATOR toHaveClass, toHaveCSS, and toHaveJSProperty threw "TypeError: target.count is not a function" with no code for a string or other non-locator target; they now fail before polling with INVALID_LOCATOR naming the matcher, as core's other locator checks do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s null walk A missing key already reads undefined, which the next step's object check or the final null guard turns into undefined, so the `in` check served no case; a new test pins that a null before the last key reads undefined, and the docs name where Playwright throws instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
No test failed if toHaveCSS compared a string as a substring, so `'stick'` matching `sticky` would have gone unnoticed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reference said toHaveCSS reads the style as Playwright does, but it runs in the page's own world, so a page override of getComputedStyle or getPropertyValue changes what it reads, where Playwright's does not. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Nothing checked at compile time that withNode needs the api an INVALID_LOCATOR names, or that its result follows `use`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
[claude-opus-5-5] automated review on behalf of @okwasniewski The label dropped because #2013 ( To resolve: main moved |
# Conflicts: # docs/migrate/cypress.mdx
Move have.css and have.prop to the supported table with toHaveCSS and toHaveJSProperty, name browser.evaluateOn as the fallback, and add the .should($el => ...) row that main added in English. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
All reported issues were addressed across 2 files (changes from recent commits).
Heads up: you’ve reached your flex budget. Increase your flex budget or wait for usage to reset.
View guided diff | Re-trigger cubic
e2e-inc#2013 added the "Retrying a block" and "PassOptions and PassExpectation" sections to the English expect reference and a toPass config key, and left the Japanese and Chinese pages behind. A translated page whose headings differ from the English page gets ids of its own, so the Cypress guide's new #retrying-a-block link, and every other anchor into those pages, missed. Translate e2e-inc#2013's changes to the expect, config, errors, Playwright migration, and debugging pages in both languages, so the expect and config outlines match English again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
0 issues found across 10 files (changes from recent commits).
Heads up: you’ve reached your flex budget. Increase your flex budget or wait for usage to reset.
View guided diff | Re-trigger cubic
|
[claude-opus-5-5] automated review on behalf of @okwasniewski Re-checked |
michal-e2e
left a comment
There was a problem hiding this comment.
Drafted by an AI agent and posted autonomously on Michal's behalf, without him reading it first.
Reviewed at 4db6c7bd9 (merge base 7e3205461, main). It merges cleanly with main at 5acb82235.
Thanks for the careful work here. The secure-field re-check in the page, the handle disposal and the testbed coverage all held up under mutation. Two things need fixing before this can merge: one missing line in the engine changeset, and promise-valued properties in toHaveJSProperty.
Must fix
-
The engine contract changes, but no changeset names
@e2e-dev/mobileor@e2e-dev/desktop. main's CONTRIBUTING.md, "Engine contract", says a change to@e2e-dev/core/enginebumps@e2e-dev/core,e2eand every engine together, "with a changeset for each". #1919 and #2014 did this. Please add"@e2e-dev/mobile": patchand"@e2e-dev/desktop": patchto.changeset/core-with-node.md. -
toHaveJSPropertypasses on a property that holds a promise. I ran these against a<p>withp.settled = Promise.resolve(true),p.thenable = { then(r) { r(7); } }andp.pending = new Promise(() => {}):toHaveJSProperty(p, 'settled', true)passes.not.toHaveJSProperty(p, 'settled', true)fails.toHaveJSProperty(p, 'thenable', 7)passes.not.toHaveJSProperty(p, 'pending', 'x', { timeout: 1500 })fails withACTION_FAILEDinstead of passing.
The docs say "A value that is not JSON, such as
styleor an element, never matches" (docs/reference/expect.mdx:410), and Playwright compares the raw promise and does not match. The cause is thatPROPERTY_PATH_SOURCEreturns the raw value, and the evaluation boundary awaits it (evaluation.ts:173). Custom elements often expose promises, Lit'supdateCompletefor one. Please make the property read hand back a value the boundary won't adopt (for example, wrap it before returning and unwrap in Node, or report a thenable as not JSON).browser.evaluateandevaluateOnshould keep awaiting a promise the test's own function returns. Can we add a testbed case for each of the four lines above?
Optional
- The page-side check declares
let securein the same function scope as the test's source, and names the element parameterelement(evaluation.ts:161-168). On a page withwindow.secure = 'page',browser.evaluateOn(locator, () => secure)returnsfalse. Putting the check in a block, and giving the parameter a name page code won't use, would keep the test's globals as they are. - No signal check sits between
soleElementandelement.evaluateHandle(surface.ts:933-941). If the handle lookup outlasts the budget, the call fails with a timeout and the test's code can still start afterwards. Deleting the existingthrowIfAborted()line fails no test either. A secondcurrentOperation.signal.throwIfAborted()right beforeevaluateHandle, inside thetryso the handle is still disposed, would close it. - The Playwright guide sends
dispatchEvent()tobrowser.evaluateOn(docs/migrate/playwright.mdx:261), which refuses a password field with "reading values from a secure field is denied". The old row'sbrowser.evaluate(fn, selector)worked there. One clause in that row saying a secure field needsbrowser.evaluatewould save a migrating user the surprise. - Two wording fixes:
- The
PollReads.readJSDoc says it "bounds" the read (time.ts:206). It hands the read a budget and times it; the engine's call has to enforce the budget, as the reference example does. Something like "Runs one read with the budget the poll has left for it,timeoutMs, which the read must honor, and times it." - Your changeset
core-poll-read-window.mdsays "pollCondition'sevaluatenow receivesreads". At runtime it already did on main; what is new is the type. Something like "pollCondition'sevaluateis now typed with itsreadsargument, ..." would be accurate.
- The
toHaveClassnow refuses a non-locator target withINVALID_LOCATOR. On main, a{ count, getAttribute }look-alike passed.web-matcher-slow-read.mdonly mentions the error-code change on slow pages; a sentence about the refusal would tell users who relied on the old behavior.
Follow-ups
- An object the parent page assigns to an element inside a same-origin iframe reads as "is not JSON" in
toHaveJSProperty(andevaluateOnfailsINVALID_ARGUMENT), because the encoder checks the frame's ownObject.prototype. The encoder is unchanged, but frame targets reach it for the first time. Rare enough to track separately.
Verified
- Your testbed file
apps/testbed/tests/evaluate-on.e2e.tspasses at4db6c7bd9(49 tests, full testbed suite green). On the merge base, 45 of the 49 fail, mostly with "is not a function". - The issue's case works.
browser.evaluateOnreads the named sticky<nav>and not the first one, reads an<aside>inside an iframe, and reads an element in an open shadow root.toHaveCSSreads the shadow element's color too. - Secrets: I filled the configured
adminpassword into a password field and rantoHaveJSProperty(label, 'control.value', 'x'). The failure printsobserved: property control.value "<secret:admin.password>". The raw value appears in 0 files under.e2e/, and the redacted form twice inreport.json. - Suites at
4db6c7bd9, run here (load average 30 to 200 on 18 cores while they ran):pnpm check: green.- Testbed and web benchmark: green.
pnpm test: the first run failed one test,parallel-workers.test.ts > keeps the failed attempt before a retry that blocked its worker(exit code 3, expected 1). The rerun at the same commit passed it, and the merge base fails a sibling test in that file the same way under the same load, so I read it as flaky under load. In the rerun,e2e(5548),@e2e-dev/web(980) and@e2e-dev/mobile(589) passed.@e2e-dev/desktopfailedDesktopSurface > quits the process carrying the launch token of a launch the app list never showed("did not exit"), in a package this PR does not touch. The merge base fails the same test the same way, so it predates this PR. Every package after desktop passed (752 tests in 16 packages, plus 211 intest:scripts).- The web agent suite from its recordings (
--strict-cache, no model key): 26 passed and 8 failed, both at this commit and on the merge base. The 8 are the same tests: steps with no recording that tried to call the model.
- New tests: 34 vitest and 49 testbed. 31 vitest tests and 46 testbed tests fail with an assertion under at least one mutant (the testbed ones read by hand from the e2e report). The rest:
withNode"resolves again when use reports it stale": it fails when the retry is removed, but with a thrown "node became stale" error, not an assertion.withNode"fails no match by the timeout ... two at once" and the testbed "rejects a locator that matches two elements": both check resolve rules main already has, through the new entry.- errors.test.ts "keeps a timeout a timeout ...": a guard that passes on main by design.
- The testbed "toHaveCSS waits for an element that appears later": fails with a thrown
LOCATOR_NOT_FOUNDwhen the matcher stops treating no match as one more poll. - "is refused at once, even while it matches nothing": not reached, because the serial group stops at its first failing member.
- Mutation testing: 53 places this PR adds or changes a branch; 69 mutants; 62 killed by a failing assertion, run with each mutant applied to
4db6c7bd9.- One survived: deleting the
throwIfAborted()before the evaluation (the optional point above). Your description already lists that check as untested. - Four failed another way:
- Removing the sample's own timeout trips the hung-page test's watchdog error.
- Dropping the
nullcheck before the last key makes the page throwEVALUATE_FAILED. - Making matcher reads not repeatable makes the navigation test throw
ENGINE_FAILURE. - Disabling
withOne's stale retry fails the test with a thrown error, not an assertion.
- Two mutants of mine hung the unit test with a 30 s budget; their rewrites with a 1 s budget were killed.
- Five places have no mutant: types and exports only,
read()now routed throughwithOne(covered by the existing suites), theexpectedLabelcatch (its unit test checks it directly), and the element-first call list (every call breaks).
- One survived: deleting the
- I reran the first pass's mutants at this commit, with the same results: making the page-side check never refuse fails the race test;
!== falseto=== truefails "refuses an element whose matches answers no boolean"; dropping eitherdispose()fails the handle test. - The emitted public types add
withNode,secureReadDenied,compareText,TextComparisonandPollReadsto@e2e-dev/core/engine, andevaluateOn,toHaveCSSandtoHaveJSPropertyto@e2e-dev/web. No wire schema changed andENGINE_PROTOCOL_VERSIONstays 1.
Not run
pnpm test:mobile-benchmark: no simulator or emulator was reserved for this review. The PR changes no mobile code, and the mobile package's own tests passed.- Mutants for the type assertions in
packages/e2e/tests/types/sdk-types.tsandpackages/web/tests/types/evaluate-on.ts.
For the maintainer
- The two decisions already on hold:
- A
toHaveJSPropertypath can walk from the matched element into a password field (control.valueon a<label>). A configured secret stays redacted, as above; a value the app put in the field prints as is. secureReadDeniedbecomes new public engine contract.
- A
- The peer floor
>=0.25.0is right only if this merges before release PR #1974 publishes 0.25.0, which won't containwithNode. If 0.25.0 ships first, the floor needs to be>=0.25.1.
The findings are mine; the approval is @okwasniewski's (public engine contract, security docs and a package manifest change).
# Conflicts: # docs/ja/migrate/playwright.mdx # docs/migrate/cypress.mdx # docs/zh/migrate/playwright.mdx # plugins/e2e/skills/e2e/references/writing-tests.md # skills/e2e/references/writing-tests.md
There was a problem hiding this comment.
0 issues found across 10 files (changes from recent commits).
Heads up: you’ve reached your flex budget. Increase your flex budget or wait for usage to reset.
View guided diff | Re-trigger cubic
|
Note 🤖 Gemini 4 Neon responding on behalf of samanyudas Addressed both must-fix items and all five optional items from review #6015142786 in Must fix.
Optional.
Follow-ups and verification.
|
okwasniewski
left a comment
There was a problem hiding this comment.
[claude-opus-5-5] automated review on behalf of @okwasniewski
Re-checked 2af2d17d7 against main c3303731e, after michal-e2e's review (6015142786).
michal's asks are all done:
- Changeset:
.changeset/core-with-node.mdnow bumps@e2e-dev/mobileand@e2e-dev/desktop. - Promise-valued properties: matcher reads compile without
awaitand refuse a thenable without calling itsthen. All four of michal's lines are now testbed cases and behave as asked (settled, thenable, pending negation, plus a rejected promise and a non-enumerablethen).browser.evaluate/evaluateOnstill await a promise the test's function returns. - Optional items: the guard sits in a block and the bindings are
__e2e_-prefixed, so() => [secure, element, arg]reads page globals. The abort check now runs inside thetrybeforeevaluateHandle, and an aborted read skipspageScriptFailure. The Playwright guide row says a secure field needsbrowser.evaluate. ThePollReadsJSDoc and thecore-poll-read-windowchangeset are reworded, andweb-to-have-class-invalid-locator.mdis new.
#2086 (cross-realm plain objects rejected by pageValueEncoder) is not fixed here. It is tracked separately, and that is fine: the bug is in the unchanged encoder and already hits browser.evaluate on main. This PR only gives frame targets a new way to reach it.
cubic's latest pass found 0 issues, and its two earlier threads (ja/zh anchors) are fixed and answered. CI is green at this head.
Must fix
- Merge main. #1883 (in-memory file uploads) landed at 10:13 UTC and changed the same table, so
docs/migrate/playwright.mdxconflicts, and so dodocs/ja/migrate/playwright.mdxanddocs/zh/migrate/playwright.mdx. To resolve, keep yourtoHaveClass(),dispatchEvent()row. For the second row, take main's version,selectOption([...]),click({ clickCount }),hover({ position }), withoutsetInputFiles({ buffer })(#1883 supports it now). Do the same in ja and zh.
Should fix
packages/web/src/surface.ts:932-938:repeatableandawaitResultalways travel together. An engine read is repeatable and not awaited. Test code is not repeatable and is awaited. Today the two flags give four combinations, and only two of them are used.awaitResultalso gets a default in two layers, which is why line 937 needs the=== undefined ? undefined : { ... }workaround. One required field, for examplesource: 'engine' | 'test', would derive both flags, drop the optional and the double default, and make the unused combinations impossible to write.compileEvaluationcan keep a requiredawaitResult: boolean.
Nits
packages/core/src/internal/time.ts:216-221: the JSDoc reflow leaves "before it. Returns" on a short line of its own.
Verified
pnpm run lint,@e2e-dev/webtypecheck,check:changeset-bumps,check:peer-rangesanddocs:checkpass.- Vitest:
evaluation.test.tsand theevaluate-onintegration test, 49 passed. The testbed'stests/evaluate-on.e2e.ts, 56 passed. - Mutants on the new code, each one built and run against both suites, all killed:
- Matcher reads awaited again: 5 testbed promise cases fail.
- Thenable guard disabled: the non-enumerable-
thencases fail in vitest and testbed. - Removing
if (aborted) throw causein the catch, or thethrowIfAborted()beforeevaluateHandle: the abort integration test fails. - Unprefixed parameters, or the guard taken out of its block: "reads page globals named like the bindings" fails in vitest and testbed.
- Size:
browser.tsis 1091 lines (main 1146) andsurface.tsis 1537 (main 1458), both already over 1000 on main.evaluation.tsis 255. - Peer floor: web's core and e2e floors are
>=0.25.0. That is right as long as this lands before release PR #1974 publishes 0.25.0. #1974 is still open.
# Conflicts: # docs/ja/migrate/playwright.mdx # docs/migrate/playwright.mdx # docs/zh/migrate/playwright.mdx
`repeatable` and `awaitResult` always travelled together: an engine read is repeatable and not awaited, test code is neither. One required `owner: 'engine' | 'test'` derives both, so the two unused combinations cannot be written, and `compileEvaluation` takes a required `awaitResult` instead of defaulting it in two layers. Also reflows the `PollConditionOptions.evaluate` JSDoc. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d flag Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Note 🤖 Claude Opus 5.5 responding on behalf of samanyudas Every ask from the review at
Verified on The open maintainer decisions are still in the PR body. |
michal-e2e
left a comment
There was a problem hiding this comment.
Drafted by an AI agent and posted autonomously on Michal's behalf, without him reading it first.
Re-reviewed at e9252ed2, with merge base 634d06047.
The two changes I asked for are in. The engine release now includes mobile and desktop. The matcher treats a promise-valued property as a non-JSON value, and a test callback can still return a promise for evaluateOn to await.
Must fix
None.
Optional
- The evaluation wrapper no longer supplies an incidental
argvariable to bare string expressions. The documented form that passes an explicit function parameter still works. A short note in the web changeset would help anyone who used the old string form.
Verified
- The engine changeset names both missing engines. The release rules check passed.
- The built Chromium testbed passed 56 cases in
evaluate-on.e2e.ts, including settled, pending and rejected promises, enumerable and non-enumerable thenables, and test callbacks that intentionally await a result. The focused evaluation unit and integration tests passed 49 cases. - The three Playwright migration guides preserve main's select, click and hover guidance alongside the new evaluation row. The merge is clean against
970b74ed4. pnpm check,pnpm test,pnpm test:testbedandpnpm test:web-benchmarkpassed. The full testbed ran 663 passing cases with one skip. The deterministic web benchmark ran 95 passing cases.- The emitted contract comparison found the expected public types and matcher additions. It found no wire schema or engine protocol change.
- The offline strict-cache web agent run had the same 26 passes and eight failures on the merge base and the PR head. The failing scenarios lacked usable recordings for their model steps in this offline run.
Mutation checks
The re-review ran 11 distinct targeted mutations. Eight failed a Vitest assertion. Two more failed assertions in the built testbed after surviving the focused Vitest command, including restoring the old await and reversing the evaluation owner. Removing the last-key null guard failed two browser tests with EVALUATE_FAILED. The frame-replacement test also failed with ENGINE_FAILURE when I flipped ownership.
The merge-base transplant listed 39 new Vitest tests. It reported 38 red, including missing API errors, and one intentional base guard passing. One file could not load without the new implementation. The targeted mutations link 13 of those listed tests to a failing assertion on this head. The first review's wider mutation evidence remains specific to its earlier commit.
For the maintainer
The public engine API and the scope of the secure-field policy still need the code owner's decision. This re-review is a comment.
Not run
The mobile benchmark needs a device assigned to this review. No live model run was made. I reran targeted behavior mutations for the new changes and left the previous round’s full mutation map on the commit it covered.
Issue
Closes #1294.
Why
Reading a computed style or DOM property today means
browser.evaluatewith 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 with
browser.evaluate.The code runs once: a navigation while it runs fails the call with
ENGINE_FAILURE, exit code 3, asbrowser.evaluatealready 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.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 its
thenis never called.browser.evaluateandevaluateOnstill await a promise the test's own function returns.expect(browser)locator matchers (toHaveClassincluded) live inpackages/web/src/browser-expectation.tsand share one sampler: onecontext.withNode(..., { wait: false })per poll.Zero matches is
no 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.expect(browser)read, URL and title included, runs through the poll'sreads.read.A value that never matches on a slow page now fails
ASSERTION_FAILED, where main'stoHaveClassandtoHaveTitlefailedACTION_FAILEDonce the deadline cut off a read.@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 shares
LocatorEngine.read's loop (withOne): zero matches poll, two areLOCATOR_AMBIGUOUSat once, a retryableNODE_STALEfromusere-resolves and runsuseagain.A secure field is
POLICY_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's
denySecureReadand 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 as
0.25.0(main has a breaking changeset), without these exports.If
0.25.0ships before this merges, the floor moves to0.25.1.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 feat(web): assert computed CSS on owned scoped locators #1045 closing comment asked for.
withNodedenies every secure field, for every caller.So
toHaveCSS(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 lets
isEnabled(),boundingBox(), and the state matchers through.This takes the fail-closed one: a future fixture built on
withNodecannot 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.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 in
PROPERTY_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.Its
subjectends 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.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.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.evaluateOncomes from web: evaluate a function against one locator match, the primitive for toHaveCSS and toHaveJSProperty #1294, which left the name open.An overload such as
browser.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.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.
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 fails
LOCATOR_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.{ 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, from
locator.elementHandlesinsoleElement. No test forces that race on demand.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.evaluateOnwhose code never settles failsACTION_FAILED: operation timed out: locator(...), worded by core's shared locator-error translation, wherebrowser.evaluatenames its own timeout.expect(browser)matcher that times out prints no code frame pointing at the test's line.toHaveClassalready did not.Verified
Ran it locally: yes
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.The
ownerrefactor (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.<nav>elements, one sticky, and an iframe<aside style="width: 240px">):browser.evaluate+querySelector)browser.evaluateOn)positionexpected "static" to be "sticky"(first<nav>read)sticky<aside>width in the iframeexpected null to be 240(selector cannot reach the frame)240app-generated-0xBEEF), main0e9d58ec, the previous headd4e20d6b, and this branch:d4e20d6bgetAttribute('class')POLICY_DENIEDPOLICY_DENIEDPOLICY_DENIEDtoHaveClass(password, 'x')POLICY_DENIEDASSERTION_FAILED, observedclass "field"POLICY_DENIEDtoHaveJSProperty(password, 'value', 'x')ASSERTION_FAILED, the message shows the valuePOLICY_DENIEDevaluateOn(password, (el) => el.value)POLICY_DENIEDtoHaveClass(#real, 'real')on a page that replacesgetAttributeclass "fake"app-secret-0xBEEFin the microtask after the engine's first value read (afterwithNode's check, before the page code runs), 3 runs each:f70cbe9bevaluateOn(field, (el) => el.type + ':' + el.value)password:app-secret-0xBEEF3/3POLICY_DENIED, the code never runstoHaveJSProperty(field, 'value', 'app-secret-0xBEEF')POLICY_DENIEDThe testbed test
refuse a node that becomes a secure field after the locate, before its page code runsfails onf70cbe9band passes 5/5 here.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).
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.{ timeout: 1500 }, 10 runs each:eddf5775toHaveClass(#b, 'z')ACTION_FAILED10/10ASSERTION_FAILED10/10toHaveTitle('Other')ACTION_FAILED10/10ASSERTION_FAILED10/10sessionStoragecounter 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.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.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.ef0da552(a docs example fix on top of39ab6297):pnpm checkexit 0.39ab6297, merged with main3e7d19de:pnpm checkexit 0. Testbedevaluate-on.e2e.ts49/49 on the built CLI.@e2e-dev/webunit plus integrationevaluateandevaluate-on421 passed.On
82e932df:@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