# Fixtures and Test Data — Playwright & Cypress

Source: https://www.skillbyai.com/en/e2e-testing/cy-data

> Static files, factories and tasks.

## Where test data comes from

Files in `cypress/fixtures` (often JSON) hold **static data**: load them with `cy.fixture('user.json')` or reference them in `cy.intercept(..., { fixture: 'todos.json' })`. For **dynamic data**, generate unique values per test (for example an email with a timestamp) so tests never collide. To create or reset data in the backend, call an API with `cy.request` or run Node code with `cy.task`, registered in `setupNodeEvents` in the config, which can talk to a database or seed script. `Cypress.env()` reads environment-specific values such as credentials; keep secrets out of committed config files.

## Fixtures, a seed task and unique data

Config and spec.

```typescript
// cypress.config.ts
import { defineConfig } from 'cypress';
import { resetDb, seedUser } from './scripts/db';

export default defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000',
    setupNodeEvents(on) {
      on('task', {
        'db:reset': () => resetDb().then(() => null),
        'db:seedUser': (email: string) => seedUser(email),
      });
    },
  },
});

// cypress/e2e/profile.cy.ts
describe('profile', () => {
  beforeEach(() => {
    cy.task('db:reset');
  });

  it('shows the seeded user', () => {
    const email = `user-${Date.now()}@example.com`;
    cy.task('db:seedUser', email);
    cy.fixture('profile.json').then((profile) => {
      cy.intercept('GET', '/api/profile', { ...profile, email });
    });
    cy.visit('/profile');
    cy.contains(email).should('be.visible');
  });
});
```

## Tasks must return a value

A `cy.task` handler must return a value or a promise; return `null` rather than `undefined` when there is nothing useful to send back, or Cypress reports an error.

**Quiz:** Where does code registered with on('task', ...) run?

- [x] In the Node.js process, so it can reach databases and the file system
- [ ] Inside the application under test
- [ ] In the browser console only
- [ ] On the Cypress Cloud servers

*Answer:* In the Node.js process, so it can reach databases and the file system. cy.task bridges from the browser to Node.
