# Testing Cleanup

> Prove a cleanup task deletes old rows and keeps live ones, and that a purge target drains a deleted owner's rows, on the in-memory test database.

*Canonical: https://makerkit.dev/docs/void-cloudflare/cleanup/testing*

---

Test your tasks and targets through the real wiring: the app's cleanup and outbox, pointed at the in-memory test database (PGlite with every migration). A daily run is one call; `runUntilIdle` runs the jobs it enqueued. [Testing Jobs](../outbox/testing) explains the mocks.

## A Cleanup Task

For the [14-day exports task](./tasks#recipe-delete-rows-older-than-14-days):

```ts
// apps/web/config/__tests__/cleanup.config.server.test.ts
import { db } from 'void/db';
import { expect, it, vi } from 'vite-plus/test';

import { runUntilIdle } from '@kit/outbox/testing';

import { cleanup } from '#/config/cleanup.server.ts';
import { outbox } from '#/config/outbox.server.ts';
import { dataExport } from '#/db/schema.ts';
import { testId } from '#/db/test-fixtures.ts';

vi.mock('void/db', async () => (await import('#/db/test-database.ts')).testDatabase());
vi.mock('@makerkit/workers-outbox/pg', async () =>
  (await import('#/db/test-database.ts')).testOutboxConnector(),
);
// a placeholder DATABASE_URL, no queue: the run's own sweep runs the jobs
vi.mock('void/env', async () => (await import('#/db/test-database.ts')).testEnv());

const DAY = 24 * 60 * 60 * 1000;

// what crons/cleanup.ts does at 03:00, then every job it enqueued
async function dailyRun() {
  await outbox.schedule(cleanup.schedule)({ cron: '0 3 * * *', scheduledTime: Date.now() });
  await runUntilIdle(outbox.getOutbox());
}

it('deletes exports older than 14 days and keeps recent ones', async () => {
  vi.spyOn(console, 'info').mockImplementation(() => undefined);

  const userId = testId('alice');

  await db.insert(dataExport).values([
    { userId, fileKey: 'old', createdAt: new Date(Date.now() - 15 * DAY) },
    { userId, fileKey: 'recent', createdAt: new Date(Date.now() - 13 * DAY) },
  ]);

  await dailyRun();

  const left = await db.select({ fileKey: dataExport.fileKey }).from(dataExport);

  expect(left).toEqual([{ fileKey: 'recent' }]);
});
```

- Put the test next to the config (`config/`), never in `crons/` (Void would load it as code).
- Always keep a row that must survive: a task that deletes too much is the bug that matters.
- A wrong task (duplicate name, a `where` that returns nothing) throws when the file imports `config/cleanup.server.ts`, so the test fails before it runs.

## A Purge Target

For the [events target](./purge-targets#recipe-purge-an-organizations-events):

```ts
// apps/web/config/__tests__/cleanup.purge.server.test.ts
import { eq } from 'drizzle-orm';
import { db } from 'void/db';
import { expect, it, vi } from 'vite-plus/test';

import { runUntilIdle } from '@kit/outbox/testing';

import { event, organization } from '#/db/schema.ts';
import { anOrganization } from '#/db/test-fixtures.ts';
import { requestPurge } from '#/lib/cleanup.server.ts';
import { getOutbox } from '#/lib/outbox.server.ts';

vi.mock('void/db', async () => (await import('#/db/test-database.ts')).testDatabase());
vi.mock('@makerkit/workers-outbox/pg', async () =>
  (await import('#/db/test-database.ts')).testOutboxConnector(),
);
vi.mock('void/env', async () => (await import('#/db/test-database.ts')).testEnv());

it("purges a deleted organization's events and keeps the others'", async () => {
  vi.spyOn(console, 'info').mockImplementation(() => undefined);
  vi.spyOn(console, 'warn').mockImplementation(() => undefined);

  const gone = anOrganization({ id: 'gone', name: 'Gone' });
  const kept = anOrganization({ id: 'kept', name: 'Kept' });

  await db.insert(organization).values([gone, kept]);
  await db.insert(event).values([
    { organizationId: gone.id, type: 'signed_in', data: {} },
    { organizationId: kept.id, type: 'signed_in', data: {} },
  ]);

  await db.transaction(async (tx) => {
    await tx.delete(organization).where(eq(organization.id, gone.id));
    await requestPurge({ tx, ownerKind: 'organization', ownerId: gone.id });
  });
  await runUntilIdle(getOutbox());

  const left = await db.select({ organizationId: event.organizationId }).from(event);

  expect(left).toEqual([{ organizationId: kept.id }]);
});
```

This example deletes an owner in a transaction you control. The kit's Better Auth organization delete instead tests `prepareOrganizationPurge` before the delete in `apps/web/lib/__tests__/cleanup.server.test.ts`. `runUntilIdle` runs only what is due, so the final pass (an hour later) stays pending; the purge itself has already drained. `packages/cleanup/src/purge.test.ts` covers the time budget, a failing target, and an early worker run while the owner exists.

---

**Next:** [Running and Failures →](./running)
