Speeding up the Playwright suite from 9 minutes to 2 minutes across 200+ test cases
Overlays, animations, build time, navigation, resetting state.
A test suite of ~200 Playwright tests against a React app and a FastAPI backend with SQLite storage, run locally on one worker took about 9 minutes.
The app itself is quite responsive, so I wondered why tests were taking so long. Before I attempted to optimize the tests, I tried to identify slow backend operations and improve them. While this helped a bit, it didn’t move the needle significantly. The backend wasn’t the bottleneck, so there had to be something in tests themselves.
Since computer is way faster at clicking precisely than me, it was baffling that some of my test scenarios took so long.
Playwright has great automatic waiting mechanisms built in, but if we wait for the wrong thing we might be stuck for longer than needed.
My gut feeling was that there had to be some unnecessary wait times between actions, specific to the browser, since backend was found to not be blocking. But gut feeling when optimizing isn’t enough, so I asked an agent to dig deeper and profile the test suite.
After the following changes, the test suite takes 3m40s on one worker, 58% less. On 4 workers it drops to 2 minutes.
Now this is a feedback loop one can work with.
The stack is (so you can tell how much of this carries over) Vite, React, shadcn/ui with Radix, Tailwind, a fresh browser context per test, and a FastAPI backend per worker that the tests seed through its API. But the optimizations described here can be applied to other stacks as well.
How it was measured
One run with tracing on and the JSON reporter gives everything needed:
npx playwright test --trace=on --reporter=json > report.json
Then read it in two steps: first which tests are slow, then which actions inside them are slow.
1. Rank tests by duration to pick which traces to read
A traced run leaves one trace.zip per test, ~200 of them here. Look for tests that are visibly slower than similar tests in the same file, e.g. a test that runs 3 seconds instead 800ms.
jq -r '[.. | objects | select(.tests? and .title?)
| {title, file, ms: .tests[0].results[0].duration}]
| sort_by(-.ms) | .[:20][] | "\(.ms) ms \(.file) \(.title)"' report.json
The ranking also catches slowness that no single action shows. A test that waits 200 ms on each of 15 animations has no action over 1 s, so the script in step 2 doesn’t catch them, but the test’s total time stands out.
2. Find the slow actions in the traces of the slowest tests.
A trace.zip stores the browser-side calls and their call logs are JSON lines in <n>-trace.trace. Here are three lines for one hover, exactly as they appear in the file:
{"type":"before","callId":"call@14","startTime":25925.203,"class":"Frame","method":"hover","params":{"selector":"internal:testid=[data-testid=\"nav-projects\"s]","strict":true,"timeout":3000},"stepId":"pw:api@42","pageId":"page@cccccf8356cd4379f53a172af45a8768","beforeSnapshot":"before@call@14"}
{"type":"log","callId":"call@14","time":25927.089,"message":"waiting for getByTestId('nav-projects')"}
{"type":"after","callId":"call@14","endTime":26340.82,"point":{"x":313.59,"y":26},"afterSnapshot":"after@call@14"}
callId ties the lines of one call together. endTime - startTime is its duration, here 416 ms. The log lines in between say what it was waiting for.
This script lists every call above a threshold with the last lines of its log, which is where Playwright says what it was waiting for:
// Usage: node slow-actions.mjs <min-ms> test-results/*/trace.zip
import { execFileSync } from "node:child_process";
const [minMs, ...zips] = process.argv.slice(2);
for (const zip of zips) {
// Browser-side calls and their logs live in <n>-trace.trace; test.trace holds runner steps.
const trace = execFileSync("unzip", ["-p", zip, "*-trace.trace"], { encoding: "utf8", maxBuffer: 1 << 30 });
const calls = new Map();
for (const line of trace.split("\n").filter(Boolean)) {
const e = JSON.parse(line);
if (e.type === "before") {
const target = e.params?.selector ?? e.params?.url ?? "";
calls.set(e.callId, { name: `${e.class}.${e.method} ${target}`, start: e.startTime, log: [] });
}
if (e.type === "log") calls.get(e.callId)?.log.push(e.message);
if (e.type === "after" && calls.has(e.callId)) calls.get(e.callId).end = e.endTime;
}
for (const c of calls.values()) {
const ms = c.end - c.start;
if (!(ms >= Number(minMs))) continue;
console.log(`${Math.round(ms)} ms ${c.name}\n in ${zip}`);
for (const msg of c.log.slice(-6)) console.log(` ${msg}`);
}
}
node slow-actions.mjs 1000 test-results/*/trace.zip
Tracing adds time to every action, so durations from this run overstate the real ones. For before/after numbers, run the suite again without --trace=on.
What the log lines mean:
| Log line | What is going on |
|---|---|
<div …> intercepts pointer events, retrying | Something (toast, overlay, closing menu) covers the target |
waiting for element to be stable | The target is still animating or moving |
waiting for element to be visible | The target isn’t rendered yet, or is still fading in |
navigating to "…", waiting until "load" | A page load; compare its time across tests to spot heavy pages |
waiting for scheduled navigations to finish | A click triggered navigation; the action waits for it |
Findings
There were a few major sources of slowness that could be identified and fixed.
| Fix | Time saved in whole run (~ 200 tests) | |
|---|---|---|
| 1 | Close a toast that blocked the next click | ~105 s |
| 2 | Instant animations and scrolls | ~115 s |
| 3 | Serve a built bundle instead of the dev server | ~50 s |
| 4 | Skip navigation the user wouldn’t do | ~25 s |
| 5 | Reset the database from a snapshot | ~25 s |
1. A notification sat on top of a button for 20 s
Five tests took 23–25 s each while similar tests took 2 s. The trace showed one click retrying for 19.5 s, its log repeating “element intercepts pointer events”. A toast, set to stay up for 20 s, was covering the button the test clicked next. Playwright doesn’t click through an overlay; it waits for it to go away. Nothing fails, so the test is just slow.
Your notifications settings could make them disappear sooner, for example after 5 seconds, but if they’re not closed immediately in the test, they will still lead to slower tests.
Fix: the test closes the toast immediately after it appears:
export async function dismissToast(page: Page): Promise<void> {
// If you don't own the toast component you might not be able to use the preferred data-testid
const close = page.locator("[toast-close]");
await close.click();
await expect(close).toHaveCount(0);
}
Don’t fix this with click({ force: true }) on the underlying button. It can fix the issue, but its not how users interact with the page.
If you find yourself using a force click, pause for a moment and reconsider the test.
Saved: ~105 s. Those five tests now take 1.2–2 s each, down from 23–25 s. About 1.5 s of that per test comes from the other fixes.
Takeaway: a test that is visibly slower than its siblings usually means an action is waiting for something, not a slow machine. The problem with notifications in tests can also be fixed by dropping notifications altogether from production code and using inline feedback on the triggering element instead.
2. Waiting for animations to finish
Before clicking, Playwright waits for an element to stop moving. Every menu, dialog, accordion and toast may animate up to 300 ms (usual duration of such animations, but might be longer). Depending on which components your test interacts with those animations may stack up to make a very slow test.
Fix: make your app respect the operating system’s “reduce motion” setting (prefers-reduced-motion), and then make the test browser turn that setting on. In Playwright it’s done in three steps:
1. The test browser asks for reduced motion (playwright.config.ts)
use: {
contextOptions: { reducedMotion: "reduce" },
},
2. A global CSS rule collapses CSS motion (src/index.css):
@media (prefers-reduced-motion: reduce) {
*,
::before,
::after {
animation-duration: 0.01ms !important;
animation-delay: 0ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
transition-delay: 0ms !important;
scroll-behavior: auto !important;
}
}
What this CSS does:
0.01ms, not0oranimation: none. Libraries that unmount onanimationendneed the event to fire. Withnonethe closing menu stays in the DOM, invisible, and swallows the next click.!importantbeats durations set by utility classes (duration-200,animate-in) and inline style.animation-iteration-count: 1stops infinite spinners and pulses, which otherwise never become “stable”.- The
*-delaylines matter as much as the durations: staggered entrances use delays. ::before/::after, because*doesn’t match pseudo-elements.scroll-behavior: autocovershtml { scroll-behavior: smooth }.
3. A helper for motion that lives in JS
For JS based animations that can’t be handled by CSS introduce a helper that ensures that setTimeouts and explicit scrollIntoView({ behavior: "smooth" }) calls respect the user’s reduced motion preference:
export function prefersReducedMotion(): boolean {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
export function scrollBehavior(): ScrollBehavior {
return prefersReducedMotion() ? "auto" : "smooth";
}
Used at every smooth scroll and every deliberate pause. The pause becomes zero, but the step still runs, so tests still see the end state a user sees:
el.scrollIntoView({ behavior: scrollBehavior() });
const reduced = prefersReducedMotion();
timer = setTimeout(reorder, reduced ? 0 : MY_VERY_IMPORTANT_TIMEOUT_MS);
Saved: ~115 s. Tests heavy on menus and dialogs got about 2 s faster each, and simple tests about 0.5 s.
This also helps real users who ask for reduced motion, which is why it lives in the app and not in the tests. If you can’t change the app, you can inject the same CSS from the test side with page.addStyleTag() after each navigation (or context.addInitScript() to insert it on every page), but that won’t affect the JS delays.
3. Every test loaded the app from the dev server – build once and preview instead
Each test gets a fresh browser context, so nothing is cached in the browser. The dev server doesn’t rebuild the app for every test: it transforms each source file once, on first request, and keeps the result in memory. But it serves those files as separate, unbundled ES modules, so every fresh context requests each module again, one by one. The bundle serves the same app as a few files instead of possibly hundreds of files.
Why the bundle is faster:
- Fewer requests. A page load from the dev server made 153 requests, one per module. The bundle makes 6.
- No import waterfall. The bundle’s few files are known upfront.
- No work on the server per page. The bundle is static files.
Estimated for the whole suite of 205 tests:
Dev server (vite dev) | Bundle (vite preview) | |
|---|---|---|
| Requests per page load | 153 | 6 |
| First load (dev server transforms files) | ~940 ms | ~100 ms |
| Later loads, median, idle machine | ~200 ms | ~90 ms |
| Page load during a suite run | ~430 ms | ~140 ms |
| Page loading, 223 loads | ~96 s | ~31 s |
| Build, once per test suite run | none | ~14 s |
| Whole suite | ~96 s | ~45 s (51 s less) |
Fix: build the app once per test suite run and serve the bundle with vite preview. The interactive debugging mode (--ui) keeps the dev server so code edits still show up live:
// playwright.config.ts
const useDevServer = process.argv.includes("--ui");
webServer: {
command: useDevServer
? "npx vite dev --port 8090 --strictPort"
: "npx vite build --mode development --outDir dist-test && npx vite preview --outDir dist-test --port 8090 --strictPort",
// Room for the build before the preview server answers.
timeout: 180_000,
url: "http://localhost:8090",
reuseExistingServer: false,
},
Notes:
- A separate
--outDirkeeps the test build from overwriting the production one. Gitignore it or clean up after the tests stop running. - Raise
webServer.timeout; the build now happens before the server answers.
Extra advantage using this approach is that if you edit the code while test suite runs, the app doesn’t reload and impacts tests, the tests run on a version of the app when the suite started. You can continue working while your tests run without breaking the current test run!
4. Navigation the user wouldn’t do
My test helpers navigated defensively: every step opens a menu and clicks its way to the page it needs, whatever page the test is on. Each of those actions lead to a page load, which slows down the tests. Two patterns remove it.
1. Return early when already there
A navigation helper should first check whether the page is already showing what the step needs, usually by comparing the URL:
export async function navigateTo(page: Page, path: string): Promise<void> {
const target = new URL(path, page.url());
const current = new URL(page.url());
// Already there: a user wouldn't reopen the menu to reach the page they're looking at.
if (current.pathname === target.pathname && current.search === target.search) return;
// …open the menu, click the link, wait for the URL and for the menu to close
}
2. Don’t land on a heavy page by accident
Check where page.goto("/") actually ends up. Redirects based on the user’s role or settings can send a test to the slowest page in the app, just for the test to navigate away. Start on a light page instead.
Saved: ~25 s.
5. Resetting the database between tests
My cleanup deleted each table’s rows through about 25 sequential API calls. It now restores a snapshot of the freshly seeded database through the app’s existing backup/restore endpoints: one request.
Snapshot contains the state of a freshly installed app: the schema the backend creates on startup, plus whatever every test needs and no test is about. That might be default settings, reference data, or a test user to log in as. Everything a test checks, the test seeds itself at its start, through the API.
So every test starts from the same database and builds its own data on top.
How to decide what goes in the snapshot?
- Data needed by nearly every test, so seeding it per test would repeat the same work ~200 times
- Data not what any test checks. The test should seed it; value appears in test setup and test assertion
- Data produced by the app’s own code. Create data through the API, then it can’t drift from what the app would create.
Rule of thumb: the snapshot is the state of a newly installed app. Anything a user would create belongs in the test.
State that lives outside the database, still needs its own reset.
Saved: ~25 s, from roughly 130 ms per test (more for tests that seed a lot of data) across ~200 tests.
Speed was not the only gain; the other being improved test isolation: a newly added table can no longer leak data into the next test because you forgot to clean it.
To do it you can create a test-only endpoint that copies a template SQLite file over the live one, pg_restore / CREATE DATABASE … TEMPLATE for Postgres, or a transaction rolled back per test when the tests and the server share a connection.
Applying this to another project
In order of effort:
- Measure first. One run with
--trace=on --reporter=json. Rank tests by duration to pick the outliers, then read the logs of their actions over 1 s. Time before/after on a run without tracing. - Turn on
reducedMotion: "reduce"and add the global CSS rule. Then grep for smooth scrolls and timed pauses in JS and gate them onprefers-reduced-motion. - Serve a production-style bundle instead of the dev server, and keep the dev server for interactive debugging only.
- Close overlays (toasts, popovers, banners) in test helpers the way a user would, never with
force: true. Or drop them from production code and replace with inline feedback. - Remove navigation the user wouldn’t do: start each test on a light page, avoid unnecessary navigation that triggers page loads.
- Reset the database with one snapshot restore instead of per-table cleanup.
- Rerun the suite several times to catch the races that faster runs expose.
Make slow actions fail to help you find them
Every cause above was a wait that didn’t fail. The toast cost 20 s per test, yet the test passed. So the most useful change is the one that stops the next wait from going unnoticed: set actionTimeout and expect.timeout to 3 s in playwright.config.ts. I think starting with 3 s is a reasonable staring point that gives server time to give you a response, but catches unexpected waits. Tweak it according to your needs.
export default defineConfig({
expect: { timeout: 3_000 },
use: { actionTimeout: 3_000 },
});
A click stuck behind an overlay now fails within 3 s and names the element that intercepts it, instead of quietly costing 20 s. Each slow action shows up as its own failure, pointing at the step that waited, instead of hiding under a global test timeout which tells only that this test case is slow. Calls that legitimately wait longer pass their own timeout.
Don’t settle for slow tests. Trace, track down hidden waits and eliminate them.
Apply it
Finding what’s causing your tests to be slower than they should be in your own traces is tedious to do by hand. This prompt hands the measuring and the first pass of the audit to an agent, so you only review what it finds.
You're profiling a slow Playwright suite. Find where
tests spend time waiting, not what this suite should look like.
1. Run `npx playwright test --trace=on --reporter=json > report.json`.
2. Rank tests by duration. Flag tests much slower than their siblings in the same file.
3. For flagged tests, read `<n>-trace.trace` in each trace.zip and list calls over 1 s with the last lines of their log.
4. Group the slow calls by cause, using the log lines and the code they point to (tests, helpers, config, app).
Common causes, as hints only: overlays intercepting clicks, animations not settling, a dev server instead of a built bundle, unneeded navigation, slow state reset between tests, fixed sleeps. Report whatever the traces show.
Rules:
- Only report what the traces or code show. Cite file:line and the log line.
- Tracing inflates durations; confirm savings with runs without tracing.
- Never fix a wait with force: true or by skipping a real interaction.
Output: a table of causes (cause | affected tests | evidence | estimated time saved per run), sorted by time saved. Then propose a fix for the top cause and stop and ask before changing anything.