DEV Community

TestDino
TestDino

Posted on

Playwright Mistake 13/14: You have no test cleanup strategy

Your tests create users, orders, and comments. But they never delete them.

A few runs later, your staging database is full of ghost users, orphan orders, and search results polluted with test data.

Or worse, your tests begin failing because they rely on a “clean” state that is no longer clean. Yesterday’s leftovers become today’s flaky test.

Test automation shouldn’t leave a trace. The fix is simple: create data before the test, then clean it up after. Even if the test fails.

import { test as base, expect } from '@playwright/test';

type Product = { id: string; name: string; price: number };

export const test = base.extend<{ testProduct: Product }>({
  testProduct: async ({ request }, use) => {
    const response = await request.post('/api/products', {
      data: { name: 'Test Product', price: 29.99 },
    });

    const product = await response.json();
    await use(product);

    await request.delete(`/api/products/${product.id}`);
  },
});

test('edit product', async ({ page, testProduct }) => {
  await page.goto(`/admin/products/${testProduct.id}`);
  await expect(page.getByText('Test Product')).toBeVisible();
});
Enter fullscreen mode Exit fullscreen mode

That’s the kind of cleanup strategy that keeps test suites reliable and staging data sane.

Does your test suite clean up after itself, or does it leave a mess behind?

Top comments (0)