How to Test IndexedDB-Backed Draft Autosave Without Cross-Test State Leakage
By David Frei · November 22, 2026
A reproducible browser-automation pattern for testing draft autosave stored in IndexedDB, including setup, refresh verification, and reliable cleanup between tests.
IndexedDB-backed autosave is useful precisely because it survives refreshes, tab crashes, and short-lived browser restarts. That same persistence is what makes tests slippery. If one run leaves draft data behind, the next run can pass for the wrong reason, or fail only when it starts from a polluted browser profile.
If you need to test IndexedDB-backed autosave, the core problem is not how to click Save. It is how to prove three things at once: a draft is written, it survives a reload, and the next test starts from a clean browser state. Browser automation can do all three, but only if you treat IndexedDB as persistent client-side state rather than as a normal page variable.
The first distinction that matters
IndexedDB is not session memory and not localStorage. It is a browser-managed database exposed to the page through the browser runtime. MDN’s IndexedDB overview is the right baseline here, because the persistence model explains the test failure modes:
- data can survive page reloads,
- data can survive origin-level navigation within the same browser profile,
- cleanup must be explicit,
- test isolation depends on the browser context or profile you choose, not just on opening a new tab.
That last point is where many autosave tests go wrong. A fresh page is not the same thing as a fresh browser storage state.
Bottom line
For browser automation, the most reliable pattern is:
- Start each test in a new browser context or equivalent isolated profile.
- Seed IndexedDB only when the test needs a known existing draft.
- Verify persistence by reloading the page and reading the UI back, not by inspecting IndexedDB alone.
- Clear IndexedDB at teardown when you cannot guarantee context isolation.
If the test only proves that a database write happened, it does not prove the user experience survived a refresh.
A practical test model
A draft autosave test usually has one of three goals. Pick the goal first, because the setup changes.
1. Empty start, write once
Use this when you want to prove a blank editor persists after typing.
Assertions:
- the editor starts empty,
- typing creates a draft,
- reloading restores the same content.
2. Seeded draft, resume editing
Use this when you want to prove the app can load and continue an existing draft.
Assertions:
- the seeded draft appears on first load,
- edits replace or append as expected,
- reload shows the updated content.
3. Isolation test
Use this when you want to prove one spec file or one test does not leak data to another.
Assertions:
- test A writes a draft,
- test B starts with no draft,
- both can run in any order.
This is the one that catches cross-test state leakage.
Use browser context isolation first, cleanup second
The cleanest solution is to give each test its own browser context. In Playwright, a new context is an isolated environment with separate storage. That usually gives you better isolation than trying to manually clear only the database you know about.
A minimal Playwright example looks like this:
import { test, expect } from '@playwright/test';
test('draft survives refresh', async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://app.local/editor');
await page.getByRole('textbox', { name: 'Draft' }).fill('Hello autosave');
await page.reload();
await expect(page.getByRole('textbox', { name: 'Draft' })).toHaveValue('Hello autosave');
await context.close();
});
This is the preferred pattern because the cleanup is structural. When the context closes, the storage state goes with it.
When cleanup still matters
You still need explicit cleanup if:
- your runner reuses a persistent profile,
- you are testing in a shared browser session,
- you run multiple specs against the same origin in the same storage bucket,
- your framework does not give each test a clean storage context by default.
That is where browser-automation IndexedDB state becomes a maintenance issue instead of a feature.
Seeding a draft without relying on the UI
Sometimes the test starts with a pre-existing draft, but using the UI to create that draft adds setup cost and noise. If your goal is specifically to test resume behavior, seed the database directly.
There are two practical ways to do that:
- use the app itself to create the draft in a setup step,
- inject test data with browser-side code before the page loads.
The first option is slower but closer to user behavior. The second is cleaner for setup-heavy suites, but it couples the test to your storage schema.
A simple browser-side helper for seeding can look like this in Playwright, using addInitScript and the page’s own IndexedDB API. The exact database and object-store names will be app-specific.
async function seedDraft(page, content: string) {
await page.addInitScript(({ content }) => {
indexedDB.deleteDatabase('drafts-db');
const request = indexedDB.open('drafts-db', 1);
request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains('drafts')) {
db.createObjectStore('drafts');
}
};
request.onsuccess = () => { ```typescript const db = request.result;
const tx = db.transaction('drafts', 'readwrite');
tx.objectStore('drafts').put({ content }, 'current');
tx.oncomplete = () => db.close();
}; }, { content }); } ```
Use this pattern carefully. It is not a generic recipe for every application, because real apps may use versioned schemas, multiple object stores, or app-specific serialization. The value is that it makes the dependency explicit.
Verifying persistence across refreshes
The key test is not whether the write succeeds, it is whether the restored UI state matches the prior edit after a reload.
A good autosave assertion sequence is:
- Load the editor.
- Type a unique value.
- Wait for the autosave indicator or network/db idle condition if the app exposes one.
- Reload the page.
- Assert the visible draft content.
Use the UI assertion as the primary check. If the app stores structured content, assert the rendered editor value, not just the presence of a timestamp or save badge.
await page.goto('https://app.local/editor');
await page.getByRole('textbox', { name: 'Draft' }).fill('Draft 42');
await page.reload();
await expect(page.getByRole('textbox', { name: 'Draft' })).toHaveValue('Draft 42');
If the editor is a rich text surface, you may need a contenteditable locator or an application-specific serialization check. The point is the same: verify what a user sees after the reload.
How to clear IndexedDB between tests
If you cannot rely on isolated browser contexts, clear the origin’s databases in teardown.
There is no single universal API on the page that wipes all storage. You need a helper that iterates known databases for the origin and deletes them.
In browsers that expose indexedDB.databases(), you can do this from page context:
async function clearIndexedDb(page) {
await page.evaluate(async () => {
if (!indexedDB.databases) return;
const dbs = await indexedDB.databases();
await Promise.all(
dbs
.filter(db => db.name)
.map(db => new Promise<void>((resolve, reject) => {
const req = indexedDB.deleteDatabase(db.name!);
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
req.onblocked = () => resolve();
}))
);
});
}
Two cautions:
indexedDB.databases()is not equally available in every browser or automation stack.- deleting while the app still has an open connection can trigger a blocked deletion.
If deletion is blocked, close the page first, then retry from a fresh context. That often tells you the app is keeping a live connection open longer than expected.
Failure modes worth testing explicitly
Autosave code often looks stable until one of these edge cases shows up.
Reload before write flushes
If the app writes on a debounce timer, a test that reloads too quickly can race the pending write. This is not a flaky test if the product actually loses data in the same scenario. The fix is to wait for the save condition the app promises, not an arbitrary sleep.
Schema migration changes the store shape
When the app bumps its IndexedDB version, an old database may behave differently from a fresh one. Add one test with an existing database from the previous schema if your release process upgrades live client state.
Cross-origin assumptions
IndexedDB is scoped to origin. If your app uses multiple subdomains or embeds an editor in an iframe from another origin, isolate the origin you are testing. Do not assume one page’s cleanup reaches another origin’s database.
Persistent profile reuse in CI
If the runner reuses a browser profile across jobs, one failed teardown can contaminate unrelated specs. This is the easiest way to get a test that passes locally and fails only in CI.
A small decision table
| Situation | Preferred approach | Why |
|---|---|---|
| Each test can get a fresh browser context | Isolate by context | Simplest cleanup, lowest leakage risk |
| Need a known existing draft | Seed storage or create via setup | Reproducible resume behavior |
| Context isolation is not available | Explicit IndexedDB deletion | Prevents state carryover |
| App has complex schema or encryption | Use UI-based setup or app-level test hooks | Direct injection may be brittle |
| Need to verify real user behavior | Reload and assert the UI | Validates persistence, not just storage writes |
What I would choose by default
For most web apps, I would start with isolated browser contexts plus one helper that clears IndexedDB as a fallback. That gives you the best balance of reproducibility and maintenance cost.
If the team controls the app and can expose a test-only reset hook, that is even better than raw database manipulation. A reset hook is app-level knowledge, which is exactly where storage schema knowledge belongs. The more your tests depend on object store names and key paths, the more brittle they become when the app changes its persistence layer.
If your framework makes browser storage cleanup awkward, that is a strong signal to prefer a runner or setup model that treats persistent state as a first-class test concern rather than as an afterthought.
Who should skip direct IndexedDB seeding
Do not seed IndexedDB directly if:
- the app encrypts draft contents client-side,
- the schema is intentionally hidden behind application logic,
- a single draft requires several related stores to stay consistent,
- you only care about the end-user workflow and not the storage layer.
In those cases, use the UI to create the draft or add a test-only app hook. Direct storage writes can make the test shorter, but they also increase the chance that the setup no longer matches the app’s real invariants.
FAQ
Should I clear localStorage and sessionStorage too?
Yes, if your editor uses them for preferences, feature flags, or draft metadata. IndexedDB cleanup alone does not guarantee a clean client state.
Is reloading enough to prove autosave works?
Reloading is necessary, but not sufficient. You also need a unique draft value, a wait for the save path to complete, and a fresh storage state at test start.
Is deleting the database in teardown safe?
Usually yes, but only after the app has closed its open connections. If deletion is blocked, close the page or use a new context and retry.
Should I assert on IndexedDB contents directly?
Only as a secondary check. The primary assertion should be the restored UI after reload, because that is the user-visible contract.
What if the app uses a service worker or offline queue too?
Treat that as a separate persistence layer. IndexedDB may hold the draft, but a service worker can delay, replay, or transform writes. Test the visible outcome and the offline behavior separately.