Most Playwright tutorials show you the happy path on a normal web app: fill a form, click submit, assert some text appeared. A dApp breaks that model in three places at once — there's a wallet the browser doesn't actually have, a transaction that confirms on its own schedule, and a failure path (a rejected signature, a reverted call) that matters as much as the success path.
Here's what actually works, with real test cases.
Test case 1: the wallet doesn't exist — inject it
A CI runner has no MetaMask, no seed phrase, no extension. The fix is
page.addInitScript — it runs before any page script, so you inject a fake
window.ethereum before your dApp's code ever checks for one.
await page.addInitScript(() => {
window.ethereum = {
isMetaMask: true,
selectedAddress: "0xAbC1230000000000000000000000000000dEaD",
request: async ({ method }) => {
if (method === "eth_requestAccounts")
return ["0xAbC1230000000000000000000000000000dEaD"];
if (method === "eth_chainId") return "0x89"; // Polygon
throw new Error(`unhandled method: ${method}`);
},
on: () => {},
};
});
await page.goto("/");
await page.getByRole("button", { name: "Connect Wallet" }).click();
await expect(page.getByText("0xAbC1...dEaD")).toBeVisible();
This is the one piece of infrastructure every other dApp test depends on. Get it wrong and every downstream test fails for the wrong reason.
Test case 2: the transaction confirms on its own schedule
A normal E2E assertion runs the instant the previous line finishes. A
transaction doesn't work that way — it sits in a mempool, gets mined, and
your UI polls for a receipt. The instinct is to reach for
page.waitForTimeout(5000) and hope five seconds is enough.
It isn't, reliably. Sometimes it's 2 seconds, sometimes 15 — and a fixed sleep either flakes under load or wastes time on every fast run.
await page.getByRole("button", { name: "Retire Credit" }).click();
// don't: await page.waitForTimeout(5000);
// do: poll for the actual UI state that means "confirmed"
await expect(async () => {
const status = await page.getByTestId("tx-status").textContent();
expect(status).toBe("Confirmed");
}).toPass({ timeout: 30_000, intervals: [500, 1000, 2000] });
toPass retries the whole block until it succeeds or the timeout hits,
backing off between attempts. It waits exactly as long as needed and no
longer — the fix for "flaky because too short" and "slow because
over-cautious" at the same time.
Test case 3: connecting the wallet on every single test is wasteful
Wallet-connect is usually 3-4 steps (open modal, pick provider, approve, wait for the address to render). Repeating that in every test file works, but it's slow and it means a wallet-connect regression fails fifty tests instead of one.
Playwright's storageState fixes this the same way it fixes logged-in
sessions on normal web apps — connect once, save the state, reuse it.
// global-setup.ts — runs once
async function globalSetup() {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.addInitScript(injectMockWallet);
await page.goto(BASE_URL);
await page.getByRole("button", { name: "Connect Wallet" }).click();
await page.context().storageState({ path: "wallet-state.json" });
await browser.close();
}
// playwright.config.ts
export default defineConfig({
globalSetup: require.resolve("./global-setup"),
use: { storageState: "wallet-state.json" },
});
Every test now starts already-connected. Wallet-connect itself still gets its own dedicated test — it just isn't repeated as a precondition for everything else.
Test case 4: test the rejection, not just the approval
This is the one most suites skip, and it's the one that matters most for a dApp specifically. A user rejecting a signature isn't an edge case — it's a completely normal, frequent outcome, and the UI has to survive it without getting stuck in a spinner forever.
await page.addInitScript(() => {
window.ethereum.request = async ({ method }) => {
if (method === "eth_sendTransaction") {
const err = new Error("User rejected the request.");
err.code = 4001; // EIP-1193 user-rejected error code
throw err;
}
return "0xAbC1230000000000000000000000000000dEaD";
};
});
await page.getByRole("button", { name: "Retire Credit" }).click();
await expect(page.getByText("Transaction rejected")).toBeVisible();
// the button must be usable again — not permanently disabled
await expect(page.getByRole("button", { name: "Retire Credit" })).toBeEnabled();
Same shape for a contract revert: mock request to throw with a revert
reason, assert the error surfaces in the UI in a form a non-technical user
can read, not a raw 0x08c379a0... selector.
The workaround flow, summarized
- No real wallet in CI →
page.addInitScriptto injectwindow.ethereumbefore the page loads. - No fixed sleeps for confirmations →
expect(...).toPass()(orexpect.poll()) against the actual UI state, not the clock. - No re-connecting on every test →
storageStateto persist a connected session across the whole suite. - No skipping the unhappy path → mock rejected signatures and reverts explicitly; assert the UI recovers, not just that it shows an error.
None of this is exotic Playwright — it's the same primitives (addInitScript,
toPass, storageState) any well-tested web app already uses. The only
difference is what they're pointed at: a wallet instead of a login form, a
block confirmation instead of an API response, a signature rejection instead
of a validation error. Once you see dApp testing as "the same discipline,
async and adversarial by default," the flaky test problem mostly disappears.