feat: add services for the app's dependencies (ENG-819)
Stacked on #2257 (defineConfig), which merged.
What
Configs can declare services with defineService, for dependencies of the app under test like an email API, an OAuth provider, or a database. e2e run and e2e explore start them before the app commands, share one instance across all workers, and stop them at the end of the run. Tests read them through the built-in services fixture.
// services/email.ts
export const email = defineService({
async *start({ signal }) {
// start a server on port 4010, passing it `signal`
yield {
url: 'http://127.0.0.1:4010',
createInbox: () => ({ address: `${randomUUID()}@example.com` }),
received: (address) => emails.filter((message) => message.to === address),
waitForEmail: async (address, { subject }) => { /* poll until one matches */ },
};
// stop it
},
});
// e2e.config.ts
export default defineConfig({
services: { email },
targets: [{ engine: web(), app: { url: 'http://127.0.0.1:0', command: {
executable: 'node', args: ['app/server.mjs'],
env: { PORT: '{port}', EMAIL_API_URL: 'http://127.0.0.1:4010' },
} } }],
});
// tests: test.extend<{}, {}, typeof config>() types the fixture
const inbox = await services.email.createInbox();
// ...sign up with inbox.address
const email = await services.email.waitForEmail(inbox.address, { subject: /welcome/i });
expect(await services.email.received(inbox.address)).toHaveLength(1);
- Tests, hooks, and fixtures of both scopes get
services. Data is copied to the workers, and every function becomes an async call back to the runner process. - Optional
startupTimeoutandshutdownTimeouton each service (defaults 60000 and 10000 ms), the same names as onapp.command. servicesis now a built-in fixture name. An engine that contributes aservicesfixture fails to load, and a project fixture namedservicesreplaces the built-in one.- New error codes:
SERVICE_START_FAILED,SERVICE_STOP_FAILED, andINVALID_SERVICE_VALUE. e2e mcpandopenHostrefuse configs with services (INVALID_CONFIG).e2e list,e2e doctor, andlaunch()don't start services.
Why
The runner could only start the app under test, through app.command. Any other dependency had to start outside the run or inside a wrapper script, and tests had no way to inspect or reset it. Services give those dependencies a lifecycle inside the run and a fixture tests can call.
How it works
flowchart LR
A[config loads] --> B[services start in key order]
B --> C[app commands spawn]
C --> D[workers get a copy of the values]
D --> E[tests call functions over IPC]
E --> F[app commands stop]
F --> G[services stop in reverse order]
- The service types live in
packages/core/src/types/services.ts.E2EConfigaddsservices, andConfigFixturestypes theservicesfixture from the config passed totest.extend.defineServicereturns the service unchanged, so the yielded value keeps its type (packages/e2e/src/config/define.ts:24). defineServicetakesserviceintersected with astartthat yieldsNoInfer<CopyableServiceValue<Value>>(packages/e2e/src/config/define.ts:24). InCopyableServiceValueandCopiedData,URL,URLSearchParams,Promise,SharedArrayBuffer,WeakMap,WeakSet, symbols, and functions in arguments and results map tonever(packages/core/src/types/services.ts:65). Maps and sets are checked before those types because aSetof objects has the shape of aWeakSet. At the top level, an array, a map, a set, a function, or a built-in likeDatemaps tonever, because only a plain object is accepted by the runner there. A class instance with only data fields, or an instance of anErrorsubclass, still typechecks, but it's refused by the runtime check.servicesis a known top-level key (packages/core/src/config/resolve.ts:169), left out of the config digest (resolve.ts:1031).resolveServiceschecks each entry by its shape instead of withinstanceof(packages/e2e/src/config/resolve-run.ts:63). It validatesstartupTimeoutandshutdownTimeoutwith the same check as other timeouts.- Before the app commands spawn (
packages/e2e/src/run/runner.ts:1154),startServicesruns each generator up to itsyieldin key order (packages/e2e/src/run/services.ts:111,startServiceat:240). A handler of the service's starting event can cancel the run, so the signal is checked again after the event (:159). The service'ssignalaborts on cancellation or after itsstartupTimeout(60 s by default). If one service fails to start, the ones that already started are stopped before the error is thrown. copyValuewalks plain objects, arrays, maps, and sets, records each function's path, and checks every other value withv8.serialize(services.ts:435). A value whose prototype changes in the copy, like a class instance or an array subclass, fails withINVALID_SERVICE_VALUE. Built-ins likeDateandBufferkeep their type. When a map or a set reaches an object that was already copied,reachesFunctionchecks the original for a function (services.ts:543), so the result doesn't depend on which path reached the object first. The top-level object of service values has a null prototype, so a service named__proto__stays a key. Workers rebuild function paths through own properties only.- Workers get the serialized values and function paths at startup and rebuild them with
copyServiceValues(services.ts:651,packages/e2e/src/run/worker/entry.ts:245). A worker process sends aservice-callmessage, and the worker handle answers with aservice-reply, so the scheduler never sees them (packages/e2e/src/run/worker/handle.ts:74). An in-process worker goes through the same copies without IPC (packages/e2e/src/run/in-process.ts:192). A thrown error comes back as a copy, with the service and function in its message and the call site's stack added. The error'smessageis copied because aDOMExceptionkeeps it in a getter thatv8.serializeskips. If reading the error throws (like a getter that throws), the reply is a plainError, so the worker always gets a reply. servicesis a worker-scoped built-in fixture (packages/core/src/run/fixtures.ts:334), so an engine fixture can't take its name. Worker fixtures are built byofWorker({ target, services }).- After the app commands stop,
stopServiceresumes each generator in reverse order (services.ts:333,runner.ts:1345). The signal stays live on a normal stop and after a first Ctrl+C. It aborts after the service'sshutdownTimeout(10 s by default). A second Ctrl+C aborts the signal of every started service at once (services.ts:128), so one service's stop code can wait on another's, and the runner stops waiting for a service that hasn't yielded. A service that still hasn't yielded when itsshutdownTimeoutpasses isn't a stop failure, since its stop code never started, so only itsSERVICE_START_FAILEDis reported. If the stop code throws, times out, or yields a second time, the run gets aSERVICE_STOP_FAILEDcleanup error. On a secondyield, the generator is ended withreturn(), so itsfinallyblocks still run. If the runner stops waiting before a service yields (on a timeout or a second Ctrl+C), the generator is still resumed in the background when it yields, so its stop code runs. e2e mcp(packages/e2e/src/mcp/session.ts:412) andopenHost(packages/e2e/src/run/open-session.ts:92) refuse configs with services withINVALID_CONFIG, before anything starts.
Docs: a new docs/services.mdx guide with an email example and an emulate Resend example (emulate@0.14.0 is a dev dependency of @e2e-dev/docs). The config, test, errors, and engine references get services entries, and the stale "no services" notes in the web docs, migration guides, and skills are updated.
Not covered yet
Two limits are out of scope for this PR:
- A service can't read another service's value. For example, a service for an AWS API emulator may need the URL of a localstack service started before it. As a possible addition, a service's
startcould receive the values of the services that started before it. - Services don't have
reuseExisting. They're started for every run and stopped at the end (even when the app process is reused). For example, if you started an emulator or database by hand on a fixed port, it won't be used. That port can't be bound, so the run fails withSERVICE_START_FAILED. As a possible addition, there could be an option to reuse a running service. You'd need a way to get the value without runningstart(such as a URL to probe and the value to use when there's a response).
Verified
Ran it locally: yes
The built CLI at this PR's head (0356358) on a scratch project with the docs email example (the email service on port 4010), three failure paths, and a service that never yields with startupTimeout: 1000:
$ e2e run
✓ service "email" ready 2ms
✓ target "web" command at http://127.0.0.1:53375/ ready 90ms
✓ |web| tests/signup.e2e.ts > signing up sends one welcome email 364ms
Tests 1 passed (1)
$ e2e run --config e2e.twice.config.ts
✓ service "email" ready 2ms
✓ service "twice" ready 0ms
ERROR infrastructure error SERVICE_STOP_FAILED (cleanup)
service "twice" yielded a second time. Yield only once, and put stop code after the yield
exit 3
$ e2e run --config e2e.instance.config.ts
ERROR configuration error INVALID_SERVICE_VALUE
service "bad" yielded an instance of Inbox at inbox, which loses its class when it's copied to tests. Put its data in a plain object
exit 2
$ e2e run --config e2e.fnprop.config.ts
ERROR configuration error INVALID_SERVICE_VALUE
service "bad" yielded an instance of Server at server, which can't be copied to tests. Put its data in a plain object
exit 2
$ e2e run --config e2e.stuck.config.ts
ERROR infrastructure error SERVICE_START_FAILED
service "stuck" didn't yield within 1 seconds
exit 3
Before the stuck-start fix, the last run also reported SERVICE_STOP_FAILED (cleanup) service "stuck" didn't stop within 10 seconds ahead of the real error, for a service that never started.
The terminal shows a line for each service only when the config declares services, so there's no main side to compare:
Without services, startServices gets an empty list and doesn't start anything.
Benchmark: pnpm bench:ab at the top of the stack (#2259, which includes this PR) against main, on two web benchmark files:
bench-ab: c3109278 (merge base with origin/main) vs b6f27edd
apps/web-benchmark: e2e run --workers 1 tests/control-inventory.e2e.ts tests/cart-totals.e2e.ts. 6 pairs in random order, resolved after 6 pairs. Threshold ±3% and 10 ms. darwin arm64, Apple M5 Pro x18, Node 24.22.1, load 4.8.
Behavior
Every test ran the same steps with the same outcome on every run of both builds.
Timings
| Metric | base median (IQR) | head median (IQR) | change (95% CI) | verdict |
|---|---|---|---|---|
| wall (process) | 4.53 s (4.48 s-4.54 s) | 4.50 s (4.41 s-4.61 s) | -0.7% (-2.6% to +3.3%) | unresolved |
| suite (sum of attempts) | 3.69 s (3.67 s-3.72 s) | 3.71 s (3.66 s-3.75 s) | -1.0% (-2.2% to +2.3%) | same |
| action (events) | 2.54 s (2.54 s-2.58 s) | 2.55 s (2.54 s-2.57 s) | -0.1% (-2.2% to +0.9%) | same, under the floor |
| step locator.longPress | 1.51 s (1.51 s-1.52 s) | 1.51 s (1.50 s-1.51 s) | -0.2% (-1.1% to +0.4%) | same, under the floor |
| step app.open | 740 ms (736 ms-743 ms) | 746 ms (726 ms-773 ms) | -1.0% (-3.5% to +5.4%) | same, under the floor |
| step locator.tap | 457 ms (447 ms-468 ms) | 470 ms (448 ms-479 ms) | +0.5% (-5.3% to +5.6%) | same, under the floor |
| step locator.check | 286 ms (276 ms-298 ms) | 296 ms (281 ms-297 ms) | -0.2% (-4.6% to +7.9%) | same, under the floor |
| step expect.toHaveText | 132 ms (129 ms-135 ms) | 130 ms (127 ms-134 ms) | +1.1% (-6.6% to +4.3%) | same, under the floor |
| step locator.scrollIntoView | 71 ms (69 ms-72 ms) | 72 ms (68 ms-72 ms) | +0.0% (-7.1% to +7.3%) | same, under the floor |
| step locator.secondaryTap | 70 ms (61 ms-79 ms) | 64 ms (62 ms-73 ms) | -8.5% (-21.0% to +25.2%) | same, under the floor |
| step locator.setInputFiles | 65 ms (64 ms-67 ms) | 63 ms (61 ms-65 ms) | -3.2% (-6.2% to -0.7%) | same, under the floor |
| step locator.doubleTap | 62 ms (61 ms-62 ms) | 63 ms (61 ms-63 ms) | +0.8% (-16.7% to +3.3%) | same, under the floor |
| step locator.uncheck | 38 ms (30 ms-45 ms) | 33 ms (32 ms-33 ms) | -14.3% (-29.7% to +31.3%) | same, under the floor |
| step app.back | 15 ms (14 ms-16 ms) | 14 ms (14 ms-15 ms) | -6.5% (-12.3% to +10.2%) | same, under the floor |
| step expect.toBeVisible | 3 ms (2 ms-3 ms) | 2 ms (2 ms-2 ms) | -33.3% (-42.3% to +41.4%) | same, under the floor |
| step expect.toBeChecked | 2 ms (2 ms-2 ms) | 3 ms (2 ms-3 ms) | 0.0% (0.0% to +73.2%) | same |
| step expect.toHaveURL | 1 ms (0 ms-1 ms) | 0 ms (0 ms-1 ms) | 0.0% (0.0% to 0.0%) | same |
Counters
Every counter matched on every run of both builds.
Tests outside the threshold: 0 of 95
With 95 tests compared at 95%, about 4.8 could land outside by chance.