Repository navigation
test(web): serve browser spec service calls from a contract-validated fake API - #46695
Merged
Merged
Conversation
Serve console API requests in tests from oRPC handlers built on the generated contract, so the real client, transport and TanStack Query run while requests and responses are validated against the contract. Pilot it on three specs that previously mocked the service module or transport.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #46695 +/- ##
==========================================
- Coverage 90.34% 90.29% -0.05%
==========================================
Files 6515 6460 -55
Lines 408603 406636 -1967
Branches 81980 81385 -595
==========================================
- Hits 369147 367174 -1973
- Misses 33051 33060 +9
+ Partials 6405 6402 -3
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
# Conflicts: # web/app/components/header/account-setting/ip-policies-page/__tests__/index.browser.spec.tsx
…HR uploads Rename the helper to installFakeApi and serve every transport the Web client uses: console and marketplace contracts, legacy REST endpoints, server-sent events, and XMLHttpRequest uploads. Migrate the upload pilot.
Replace vi.mock('@/service/...') in 159 browser specs with installFakeApi, so
requests run through the real clients and transports and are validated against
the generated contracts. Extend the helper for enterprise contract segments,
same-origin endpoints, backend-shaped error details, offline network failures,
and local data:/blob: URLs.
Fix fixtures the contracts reject (UUID ids, missing required fields, wrong
response shapes), and drop assertions that are not observable over HTTP, such as
client call options. Two specs keep their service mock because migrating them
exposed product behavior that needs a decision: page-indexing (stale polling
intervals) and authorize-account (focus lost while Approve is disabled).
This was referenced Nov 18, 2026
- Migrate page-indexing and authorize-account to the fake API and mark the failures they expose as known product bugs (#46699, #46700). - Wait for the document title in the device page spec instead of reading it once after the heading renders. - Skip the pricing infotip hover test, which flakes with fake timers, with the observed failure and re-enable condition. - Stop exporting fake API types nothing imports (knip).
…Error options installFakeApi now wraps every handler in a vi.fn spy reachable at its contract path (fake.console..., fake.marketplace..., fake.route(...)), adds fake.use() to override or add handlers mid-test, logs problems as they happen, and apiError takes an options object. Convert existing apiError calls.
Type handler spies from the contract signature, give route handlers a pre-read request body, and return typed spies from fake.use(). Convert browser specs to inline handlers asserted through fake.console/fake.marketplace/fake.route, replacing about 250 delegating spies, and align the snippet fixtures with the contract response types.
# Conflicts: # web/app/(auth)/device/components/__tests__/authorize-sso.browser.spec.tsx
…rives The ported focus-retry tests rejected the pending approval before the fake API route had picked it up under CI load, which surfaced as an unhandled rejection.
2 of 5 tasks
…nggenius/dify into test/fake-console-server # Conflicts: # web/app/components/billing/pricing/__tests__/feature-infotip.browser.spec.tsx
…ole-server # Conflicts: # web/app/components/header/account-setting/__tests__/settings-loading.browser.spec.tsx # web/app/components/header/account-setting/members-page/__tests__/delete-member.browser.spec.tsx
…ole-server # Conflicts: # web/app/components/header/account-setting/__tests__/settings-loading.browser.spec.tsx # web/app/components/header/account-setting/ip-policies-page/__tests__/index.browser.spec.tsx
…ole-server # Conflicts: # web/app/components/header/account-setting/__tests__/settings-loading.browser.spec.tsx # web/app/components/header/account-setting/permissions-page/__tests__/role-editing.browser.spec.tsx
- Coerce only URL and header values; validate JSON bodies with the types the client sent. - Report request bodies oRPC cannot decode, while keeping handler-thrown 400s. - Report custom-method paths sent in the internal ~method form. - Catch chained it.fails forms such as it.fails.each in the browser spec policy.
…es by type - Make teardown async and wait for requests still being answered, so a response that breaks the contract after the last assertion fails the test. Requests held with hold() or pendingResponse(), and requests the client aborted, are exempt; any other request still pending after 2s is reported. - Add pendingResponse() for loading states and use it for never-settling handlers. - Decode REST route bodies by Content-Type: report JSON or form bodies that fail to parse, and pass other bodies through as text.
…rough teardown - Track each fake spy's regular implementation, since getMockImplementation() returns the next queued once-implementation; release() now calls it directly and marks the request settled at once, so teardown waits for it. - Re-stub fetch and XMLHttpRequest at the start of teardown and restore them only after the in-flight wait and checks, so requests made meanwhile are still served and checked. - Report handler exceptions other than apiError() and networkError() as broken fixtures.
…R aborts - Re-stream response bodies so a request stays tracked until its body ends or is cancelled, aborting after the headers errors a body being read, and teardown waits for bodies the client is reading before restoring the real transports. - Pass the XHR abort signal to the tracked request, so teardown treats it as cancelled. - Resolve same-origin relative API prefixes against the page origin. - Catch tagged-template it.fails.each in the browser spec policy. - Serve the emoji catalog that the icon picker refetches after the test body.
…e browser spec policy
…ake-timer boundary Vitest Browser locator retries advance fake timers, so a check at exactly 2499 ms depended on how many retries the preceding assertions needed.
…in the fake API - Report form or multipart bodies sent to endpoints whose contract body has no file field, before schema validation, and answer them with 415. - Report API paths with a trailing slash, which the Flask routes do not declare. - Hold the stale preview job and wait for it to arrive before closing the edit dialog. - Resolve relative vi.mock paths before checking for service mocks in the browser spec policy.
hyoban
marked this pull request as ready for review
November 23, 2026 07:02
hyoban
requested review from
CodingOnStar,
WTW0313,
crazywoola,
iamjoel,
laipz8200 and
lyzno1
as code owners
November 23, 2026 07:02
lyzno1
approved these changes
Nov 23, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Replaces
vi.mock('@/service/...')in Web browser specs with a contract-validated fake API, so service calls run through the real clients, transports and TanStack Query, and requests and responses are checked against the generated contracts at runtime.Result: all 162 service-mocking browser specs are migrated, and no browser spec mocks
@/service/*anymore. The migration exposed two product bugs, both filed: one is covered by a test that asserts the known bug, and the other was fixed on main (see below).Problem
The service mocks (
withConsoleResponses, whole-module replacements, legacy@/service/basestubs) bypassed request serialization, error handling and the HTTP round trip, and let fixtures drift from the backend contract without any test failing.The fake API (
web/test/fake-api.ts)console/marketplace: handlers mirror the generated contract trees and are typed from them. Each is wrapped with oRPCimplement()and served byOpenAPIHandler. Console segments load through the app's ownloadConsoleContractForSegment, now exported, so the enterprise segment works too.vi.fnreachable at its contract path (fake.console...,fake.marketplace...), typed from the contract signature. Tests can assert on the decoded request input, or return a deferred withmockReturnValueOnce, without hand-made spies.setupFakeApi(api | () => api): installs a fresh fake before each test in the file and tears it down afterwards; the handle always points at the current test's fake.installFakeApi+onTestFinishedremains for fakes built from per-test arguments.{ body },{ params },{ query }), so assertions don't needexpect.objectContaining. Procedures without an input schema drop transport headers and empty parts.pendingResponse(): a response that never arrives, for loading states; teardown treats it as deliberately held.hold(spy): keeps the spy's next request pending and returns{ arrived, resolve, reject, release }.release()answers with the handler's regular implementation (tracked by the fake, since Vitest'sgetMockImplementation()returns the next queued once-implementation), and teardown waits for it. Settling before the request arrives is safe, so a rejected hold never becomes an unhandled rejection.fake.use(...): overrides or adds handlers mid-test and returns typed spies for the ones it adds.routes:route(method, 'console' | 'public' | 'marketplace' | 'origin', '/path/:id', handler)serves endpoints without a contract: legacy@/service/basecalls, share and public APIs, and same-origin device-flow URLs. Route handlers and spies receive the requestbodydecoded byContent-Type: JSON (application/jsonorapplication/*+json, as Flask reads it),FormData, or text; a JSON or form body that fails to parse fails the test.fake.route(method, base, path)returns a route's spy./console/api,/api) are resolved against the page, like the app's clients do.fetchis stubbed, and so isXMLHttpRequest, which legacy uploads use. Both follow native behavior where clients depend on it: an abortedfetchrejects with the signal'sAbortError(before or while the response is pending) and errors a body still being read, an aborted XHR cancels its tracked request, and an XHR withresponseType = 'json'and a non-JSON body completes withresponse = null.sseResponse([...])streams SSE.data:andblob:URLs pass through natively.apiError({ status, message, code?, details? })answers in the Python API's{ code, message, status, ...details }shape.networkError()fails a request like an offlinefetch. Any other exception from a handler is reported as a broken fixture.hold()orpendingResponse(), or aborted by the client), then fails the test on input or output contract violations, request bodies that cannot be decoded (a handler's ownapiError({ status: 400 })is still allowed), form bodies sent to JSON endpoints (only bodies with a file field accept forms; answered with 415), bodies Flask would not read as JSON (noContent-Type, or a type other thanapplication/jsonorapplication/*+json; also answered with 415), paths with a trailing slash the Flask routes do not declare, requests still pending 2 s after the test, requests within an API prefix that no handler answers, and any other network request. Each problem is also logged when it happens.SmartCoercionPlugin; JSON bodies keep the types the client sent, since the Python API validates them strictly), repeated-key arrays (using the client's own rules, now exported fromopenapi-url.ts), and header-name casing such asIdempotency-Key. Custom-method paths that put a parameter and a literal in one segment (/workflows/{workflow_id}:precheck), which oRPC's router cannot match, are split into separate segments on both sides; a request that arrives in that internal~methodform is reported, so the client must still send the contract's:methodpath.Asserting through these spies replaced about 250 delegating spies (
(input) => api.x(input)) across the migrated specs. The snippet fixtures are now typed as the contract response types.Across the specs: 70 files moved to
setupFakeApi, 26 hand-made deferreds becamehold(), the 8getMockImplementation()workarounds becamehold(...).release(), and 33objectContainingwrappers on spy assertions were removed where the input is exact. Shared fixtures now use UUIDs for IDs that appear in request paths: workspace, IP policy, app, agent, dataset, snippet, access policy and roles (web/test/console/ids.ts). Specs no longer copy their own UUIDs to get past the old defaults; for example, the same dataset UUID had been pasted into 6 specs.Guardrails
check-browser-spec-policy.tsnow rejectsvi.mock('@/service/...')in browser specs (even with a boundary comment, and in thevi.mock(import('…'))form, and when the path is relative, such as../../service/console) and directfetch/XMLHttpRequeststubs (vi.stubGlobal,vi.spyOn(globalThis, …), assignment). Before this, service mocks were outside the policy's owned-path rule, which is how new ones kept arriving from main.guardUnexpectedFetchwhere no request is expected. The voice-input spec's mock of the feature-owned transcription wrapper (which callsconsoleClient) was moved to the fake API too.it.fails(including chained and tagged-template forms such asit.fails.each, and the{ fails: true }option) in specs that use the fake API, whichever path imports it: Vitest inverts the fake's teardown failures too, so a contract violation would be recorded as the expected failure. Known product bugs are covered instead by a normal test that inverts only the assertion showing the bug, with aTODOlinking the issue (Agent credential selection drops keyboard focus while credential info refetches #46384, AudioPlayer hidden unavailable overlay blocks pointer input #45655). The New RAG overview keeps polling metrics after indexing tasks finish #46699 journey is skipped instead, because inverting it would make continued polling a passing condition.tag_ids[0]=…) for the repeated-key arrays the Python API reads withgetlist(), since the backend would ignore them.web/docs/test.mdhas a new "API Data in Browser Specs" section on how to use the fake.What the migration found
{}for void responses, and invalid enum values. Spec-local data was fixed in place; the shared fixtures' ID defaults are now fixed at the source (see above).{ context: { silent: true } }are dropped, because they aren't observable over HTTP.Errors becameapiError(...), ornetworkError()where the scenario is offline.Product bugs found
page-indexing.browser.spec.tsxthat catches it is skipped here with the correct assertion; fix(web): stop new RAG overview polling after tasks finish #46747 fixes the polling and turns the test back on.<body>while Approve is pending. It has since been fixed on main by fix(web): keep focus on pending device authorization actions #46701; after merging main, that test passes, and fix(web): keep focus on pending device authorization actions #46701's new focus tests are ported to the fake API.Other CI fixes
page-terminal: waits fordocument.titleinstead of reading it once, which raced under CI load.feature-infotip: the hover re-anchoring flake from test(web): tighten browser specs to the Browser Mode testing contract #46688 was fixed on main by test(web): make pricing infotip reanchor test deterministic #46721; this branch takes that fix instead of skipping the test.Dependencies
Adds test-only devDependencies pinned to the existing oRPC version (1.16.2):
@orpc/server,@orpc/openapi,@orpc/json-schema,@orpc/zod.Prior art
Supabase Studio requires network-level mocks typed from its OpenAPI paths and forbids mocking the data layer. Grafana and Backstage mock at the network level with MSW. oRPC's official
@orpc/mswfollows the same idea but is only published for oRPC 2.0 beta; the handler shape here would carry over.Verification
vp test run --project browser --maxWorkers=2 <files>, giving 806 tests passed, 3 expected fails and 1 skipped. Specs touched by the main merge were rerun afterwards, and timing-sensitive specs were also run individually two to five times.vp test run --project unit test/__tests__/fake-api.spec.ts, 23 tests; policy script tests, 27 tests.crawl-selection-form(navigation asserted before the request), now fixed and passing 3 of 3 runs.vp checkon every changed file,check-browser-spec-policy.ts, andpnpm knip.Checklist
make lint && make type-check(backend) andvp staged(frontend) to appease the lint gods