Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 35 ยท Actions and Assertions

Forms, Uploads and Downloads

Test forms end to end in Cypress and Playwright: filling fields, validation messages, radios, dates, file uploads with selectFile and setInputFiles, and downloads.

Forms are where users give your application data, and where most of the bugs live: a required field that is not enforced, an error message that never clears, an upload that silently drops large files. They are also the part of a test suite that rewards care, because a form test exercises the whole stack: markup, validation, network and feedback.

This lesson shows how to fill every kind of control, how to test validation (including the browser's native messages), how to attach files in both tools, and how to check a download. It uses the action commands from Clicking, Typing and Other Actions and the retrying assertions from Assertions That Retry.

Real versus stand-in. The Cypress (js) and Playwright (ts) code in static blocks is real and read-only, because the site cannot run a browser or serve files. The runnable example is a small form model with validation rules and a fake file input. It shows which checks a form performs and what a test should assert, not how a browser implements them.

Filling the basics

Text, email, password and textarea fields all work with the same commands. Always find fields by label when you can.

JavaScript
// Cypress
cy.findByLabelText('Full name').type('Ada Lovelace');        // Testing Library query
cy.get('[data-cy=email]').type('[email protected]');
cy.get('[data-cy=bio]').clear().type('Mathematician.');
TypeScript
// Playwright
await page.getByLabel('Full name').fill('Ada Lovelace');
await page.getByLabel('Email').fill('[email protected]');
await page.getByLabel('Bio').fill('Mathematician.');

findByLabelText comes from the optional Testing Library plugin; plain Cypress uses attributes or cy.contains('label', 'Full name'). Playwright's getByLabel is built in.

Checkboxes, radios and selects

Radios and checkboxes are covered by check(); selects by select() (Cypress) and selectOption() (Playwright). Choose radios by their label so the test reads like the page.

JavaScript
// Cypress
cy.get('[data-cy=plan-pro]').check();
cy.get('[data-cy=terms]').check();
cy.get('[data-cy=country]').select('Norway');
TypeScript
// Playwright
await page.getByLabel('Pro plan').check();
await page.getByLabel('I accept the terms').check();
await page.getByLabel('Country').selectOption('NO');   // by value; use { label: 'Norway' } for text

For a radio group, assert the group state with toBeChecked() (Playwright) or .should('be.checked') (Cypress) on the one you chose, not on a count of checked inputs.

Date and time inputs

Native <input type="date"> is picky: its value is always yyyy-mm-dd, regardless of how the browser displays it. Both tools set the value in that format.

JavaScript
cy.get('[data-cy=birthday]').type('1990-03-15');          // Cypress
TypeScript
await page.getByLabel('Birthday').fill('1990-03-15');     // Playwright

Custom date pickers (a calendar widget built from buttons) are different: you click the field, navigate months and click a day, like any other UI. Wrap that in a helper and reuse it.

Testing validation

Validation has three layers, and a good form test touches each.

  1. Browser built-in validation (required, type="email", minlength, pattern, min, max). The browser blocks submission and shows a bubble. The bubble is not part of the DOM, so you cannot assert on it by text. You assert on state instead: the field matches :invalid, or validationMessage is non-empty, or the submit handler did not run.
  2. Your own client-side messages, rendered into the page (<p role="alert">Enter a valid email</p>). These are plain DOM and easy to assert.
  3. Server-side validation, returned from the API and rendered by the app. Stub a failing response to test the display (see Intercepting and Mocking Network Requests).
JavaScript
// Cypress: native validation state
cy.get('[data-cy=email]').type('not-an-email');
cy.get('[data-cy=submit]').click();
cy.get('[data-cy=email]').then(($el) => {
  expect($el[0].validity.valid).to.be.false;                 // runs once; fine for a settled form
});
cy.get('[data-cy=email]:invalid').should('exist');           // retrying alternative

// Cypress: custom message in the DOM
cy.get('[data-cy=email-error]').should('have.text', 'Enter a valid email address');
TypeScript
// Playwright
await page.getByLabel('Email').fill('not-an-email');
await page.getByRole('button', { name: 'Create account' }).click();

const isValid = await page.getByLabel('Email').evaluate((el) => el.validity.valid);
expect(isValid).toBe(false);                        // read once; fine for a settled form
await expect(page.getByLabel('Email')).toHaveAttribute('aria-invalid', 'true');
await expect(page.getByRole('alert')).toContainText('Enter a valid email address');

Native validationMessage text differs between browsers and languages, so avoid asserting on it. Assert on :invalid, on aria-invalid, and on messages your own code renders.

Also test the good path after the bad path: fix the field and assert that the error disappears and submission succeeds. Many bugs live in stale error state.

Never post to a real server in a lesson

Throughout this tutorial the forms you test are fixtures: either a local app or a page whose submit handler prints the data. In your own suite, stub the network call or point the app at a test backend so that submitting a form cannot create real accounts or send real emails.

Uploading files

A file input cannot be typed into, because the browser forbids scripts from setting a file path. Both tools provide a command that attaches a file directly.

JavaScript
// Cypress 9.3 and later
cy.get('input[type=file]').selectFile('cypress/fixtures/avatar.png');
cy.get('input[type=file]').selectFile(['a.pdf', 'b.pdf']);               // several files
cy.get('input[type=file]').selectFile({
  contents: Cypress.Buffer.from('id,name\n1,Ada'),
  fileName: 'people.csv',
  mimeType: 'text/csv',
});
cy.get('[data-cy=dropzone]').selectFile('cypress/fixtures/avatar.png', { action: 'drag-drop' });
TypeScript
// Playwright
await page.getByLabel('Avatar').setInputFiles('tests/fixtures/avatar.png');
await page.getByLabel('Documents').setInputFiles(['a.pdf', 'b.pdf']);
await page.getByLabel('Import').setInputFiles({
  name: 'people.csv',
  mimeType: 'text/csv',
  buffer: Buffer.from('id,name\n1,Ada'),
});
await page.getByLabel('Avatar').setInputFiles([]);       // clears the selection

// A button that opens the native chooser instead of exposing an input:
const chooserPromise = page.waitForEvent('filechooser');
await page.getByRole('button', { name: 'Upload' }).click();
const chooser = await chooserPromise;
await chooser.setFiles('tests/fixtures/avatar.png');

Generating the file in memory (the contents and buffer forms) keeps fixtures out of the repository and lets you test edge cases such as an empty file, a huge file or the wrong extension without creating them on disk. Assert what the user would see: the file name appears, a preview renders, an error explains a rejected type. Whether the browser or the server enforces accept and size limits is an app question, so test the behavior you promise.

Checking downloads

Playwright can observe a download as an event. Start waiting before the click that triggers it, or you can miss it.

TypeScript
import { readFileSync } from 'node:fs';

const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Export CSV' }).click();
const download = await downloadPromise;

expect(download.suggestedFilename()).toBe('orders.csv');
await download.saveAs('test-results/orders.csv');

expect(readFileSync('test-results/orders.csv', 'utf8')).toContain('id,total');

Cypress does not expose download events. The browser saves the file into the configured downloads folder (downloadsFolder, cypress/downloads by default), and you read it back. cy.readFile retries until the file exists.

JavaScript
cy.get('[data-cy=export]').click();
cy.readFile('cypress/downloads/orders.csv', { timeout: 10000 })
  .should('contain', 'id,total');

Clean the folder before the test (a cy.task that deletes it) so a stale file from an earlier run cannot make a broken export pass.

flowchart LR
  A["Test fills fields"] --> B{"Browser-native<br/>validation"}
  B -- invalid --> C["Block submit<br/>(assert :invalid)"]
  B -- valid --> D{"App-level<br/>validation"}
  D -- invalid --> E["Render error in the DOM<br/>(assert the message)"]
  D -- valid --> F["Send to server"]
  F --> G["Success or server error"]

Layers of form validation. A thorough form test aims at each exit.

A form model with validation

The stand-in below models a sign-up form. A table of rules checks required fields, length, a pattern, a date format and range, a radio-style choice, a required checkbox, and a file with an allowed type and maximum size. submit() returns either errors per field or the data that would be posted. Run it and read the five scenarios: empty, wrong values, wrong file type, file too large, success.

JS Validate a sign-up form, step by step

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare each scenario with what an end-to-end test would do. Step 1 clicks submit on an empty form and asserts that every required field complains. Steps 3 and 4 use setInputFiles with in-memory files (a .txt and an oversized .png), the pattern you saw above. Step 5 asserts the success path. Notice that the messages are written for people; a test asserts on stable parts of them, or on an attribute such as aria-invalid, so that harmless rewording does not break the suite.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a test usually not assert on the exact text of the browser's native validation bubble?

    The bubble is drawn by the browser, outside the DOM. Assert on :invalid, validity or aria-invalid, and on messages your own code renders.
  2. 2. In Playwright, when must page.waitForEvent('download') be called?

    The event fires when the download starts. Create the promise first, click, then await the promise, otherwise the event can be missed.
  3. 3. What format must the value of a native date input use when you set it with fill() or type()?

    The value of input type=date is always yyyy-mm-dd, even if the browser shows a different format on screen.
  4. 4. How does Cypress usually verify a downloaded file?

    Cypress has no download event. The browser saves to downloadsFolder and cy.readFile, which retries, checks the content.

Summary

  • Fill fields by label; use check() for boxes and radios and select() or selectOption() for dropdowns.
  • Date inputs take yyyy-mm-dd; custom pickers are tested by clicking through them.
  • Test validation at three layers: browser-native (assert state, not bubble text), app-rendered messages, and server errors (stubbed). Also test recovery after an error.
  • Attach files with selectFile (Cypress) or setInputFiles (Playwright); in-memory files make edge cases cheap.
  • Check downloads with the download event in Playwright, or by reading the downloads folder in Cypress.
  • The form model is a teaching stand-in; real browsers enforce more rules and word their messages differently.

Next: Iframes, New Tabs and Dialogs.