Cleanup
Do not clean up shared cached resources in Playwright's afterAll, afterEach, or other after*
hooks. These hooks follow test and worker lifecycles, so they can delete a cached user, database
record, or other resource while another test or worker is still using it.
Instead, follow Global Cache's dedicated cleanup flow. Its cleanup callback runs after all workers
have finished, when shared resources are no longer in use. Pass the callback to globalCache.wrap()
when configuring Playwright:
playwright.config.ts
import { defineConfig } from '@playwright/test';
import { globalCache } from '@global-cache/playwright';
const config = defineConfig({
// ...your Playwright config
});
export default globalCache.wrap(config, {
cleanup: async () => {
const { removeUser } = await import('./tests/helpers/database');
const userId = await globalCache.getStale('seeded-user-id');
if (userId) {
await removeUser(userId);
}
},
});
Keep cleanup-only dependencies inside the callback so test workers do not load code they never use.
Which value is stale?
- Non-persistent key:
getStale()returns the current value, which is about to be cleared. - Persistent key: when a value was replaced during this run,
getStale()returns the previous value. The new value remains available for later runs.
These stale values remain available for the duration of the cleanup callback.
Dynamic keys
Use getStaleList(prefix) to clean a family of resources:
cleanup: async () => {
const userIds = await globalCache.getStaleList<string>('created-user:');
for (const userId of userIds) {
await removeUser(userId);
}
},