Skip to content
Back to Blog
Cypress

Rerunnable Cypress specs with faker names and prefix cleanup

A spec that passes once and fails on rerun is leaving data behind. Give every test a unique name with faker, sweep by prefix before and after.

Rerunnable Cypress specs with faker names and prefix cleanup
100% Human-Authored: All engineering insights, production war stories, and code were written by Marcelo Costa with zero AI involvement in authoring. AI was used solely for multilingual translations.

Ever met a spec that only passes once per environment? Run 1: green. Run 2: "name already exists." Or the edit test can't find its fixture anymore because yesterday's run renamed it for good.

I had a spec exactly like that: several tests sharing a couple of hardcoded names. Picture a coupons admin page. The edit test permanently renamed SPRING10, so on the next run the discard test had nothing left to open. The delete test wiped out the coupon the export test needed. And every single run left another renamed copy sitting in the environment like confetti.

One naming rule and one cleanup helper fixed the whole thing.

One prefix per spec, one random suffix per test

Everything the spec creates starts with a prefix owned only by that spec, plus a short random suffix from @faker-js/faker:

import { faker } from '@faker-js/faker';

const prefix = 'e2e_coupons_';
const uniqueCode = (scenario: string) => `${prefix}${scenario}_${faker.string.alphanumeric(4)}`;

Each test creates its own data through the API under a fresh name and never touches anything another test created:

it('discards unsaved edits to a coupon', () => {
  const code = uniqueCode('discard');
  cy.log(`coupon under test: ${code}`);

  cy.request('POST', '/api/coupons', { code, percentOff: 10 });
  cy.visit('/admin/coupons');
  cy.contains('[data-cy="coupon-row"]', code).find('[data-cy="edit"]').click();
});

Nothing fancy there. Always log the generated name, because a random-name failure saying "not found" is useless when you don't know which string it was looking for.

Sweep by prefix — both before and after

The cleanup helper lists everything and deletes every item that starts with the spec's prefix:

function removeCouponsStartingWith(prefix: string) {
  cy.request<Array<{ id: string; code: string }>>('GET', '/api/coupons').then(({ body }) => {
    const leftovers = body.filter(coupon => coupon.code.startsWith(prefix));
    cy.log(`removing ${leftovers.length} leftover coupon(s)`);
    leftovers.forEach(coupon => cy.request('DELETE', `/api/coupons/${coupon.id}`));
  });
}

Then wire it into both hooks:

before(() => removeCouponsStartingWith(prefix));
after(() => removeCouponsStartingWith(prefix));

You're probably thinking: "why call the same cleanup twice?" Because each hook does a different job:

after()  → keeps the environment tidy after a normal run
before() → cleans up the mess when a previous run got killed halfway and after() never fired

before() is the one that actually saves you.

Two runs of the same spec: the first leaves an object behind and fails the rerun; with unique names and a prefix sweep in before and after, both runs pass

Why not just delete and recreate the same fixed name?

I tried that first, and it failed in the sneakiest way possible. Delete-and-recreate trusts the delete. I have met a delete endpoint that answers 200 even when the delete fails on the server (fun, right?), next to a create endpoint that rejects duplicate names. So when a delete quietly failed, recreating the same name left the old record in place, and the test happily opened yesterday's object with yesterday's state, only to blow up a minute later on an assertion that looked completely unrelated.

With a fresh name per test, that failure mode disappears. Whatever survived an older run sits under a different name, and the next prefix sweep wipes it out.

How I prove it's rerunnable

Run the spec twice in a row on the same environment without resetting anything — both runs must come back green. Then start a third run, kill it halfway with Ctrl+C in headless mode, and run it once more: the before() sweep should log the leftover IDs it cleaned up. If run 2 hits a duplicate or missing fixture, some test in the file is still holding onto a fixed name.

Full rerunnable spec

Here is a complete spec, cypress/e2e/coupons.cy.ts, using unique faker names and a prefix sweep in both before and after:

import { faker } from '@faker-js/faker';

const prefix = 'e2e_coupons_';
const uniqueCode = (scenario: string) => `${prefix}${scenario}_${faker.string.alphanumeric(4)}`;

function removeCouponsStartingWith(couponPrefix: string) {
  cy.request<Array<{ id: string; code: string }>>('GET', '/api/coupons').then(({ body }) => {
    const leftovers = body.filter(coupon => coupon.code.startsWith(couponPrefix));
    cy.log(`removing ${leftovers.length} leftover coupon(s)`);
    leftovers.forEach(coupon => cy.request('DELETE', `/api/coupons/${coupon.id}`));
  });
}

function createCoupon(code: string) {
  cy.request('POST', '/api/coupons', { code, percentOff: 10 }).its('status').should('eq', 201);
}

describe('Coupons admin', () => {
  before(() => {
    cy.login();
    removeCouponsStartingWith(prefix);
  });

  after(() => {
    removeCouponsStartingWith(prefix);
  });

  beforeEach(() => {
    cy.login();
  });

  it('discards unsaved edits to a coupon', () => {
    const code = uniqueCode('discard');
    cy.log(`coupon under test: ${code}`);

    createCoupon(code);
    cy.visit('/admin/coupons');

    cy.contains('[data-cy="coupon-row"]', code).find('[data-cy="edit"]').click();
    cy.get('[data-cy="coupon-code"]').clear().type(`${code}_unsaved`);
    cy.get('[data-cy="discard"]').click();

    cy.contains('[data-cy="coupon-row"]', code).should('be.visible');
  });

  it('deletes its own coupon without touching any other test', () => {
    const code = uniqueCode('delete');
    cy.log(`coupon under test: ${code}`);

    createCoupon(code);
    cy.visit('/admin/coupons');

    cy.contains('[data-cy="coupon-row"]', code).find('[data-cy="delete"]').click();
    cy.get('[data-cy="confirm-delete"]').click();

    cy.contains('[data-cy="coupon-row"]', code).should('not.exist');
  });
});

Kill this spec halfway with Ctrl+C or run it five times in a row — each test owns its own fresh data, and before() sweeps whatever a dead run left behind.

Rerunnable spec lifecycle: before() prefix sweep, isolated faker-named tests, and after() prefix sweep

Recap: what you need to do

  • Give each spec its own unique prefix (const prefix = 'e2e_coupons_') and append a short @faker-js/faker suffix per test.
  • Always log the generated name with cy.log so failure messages point straight at the record.
  • Create each test's data via API under its fresh name instead of reusing or recreating hardcoded names.
  • Run the prefix sweep in both before() (recovers from aborted runs) and after() (keeps the environment tidy), then verify with two consecutive runs plus a Ctrl+C kill test.

Happy testing!