Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 35 ยท Actions and Assertions

Clicking, Typing and Other Actions

Learn the action commands in Cypress and Playwright - click, type, fill, check, select, hover, drag and keyboard - plus actionability and when force is a bad idea.

Finding an element is half of a test; the other half is doing something to it as a user would. Both tools give you commands for clicking, typing, ticking checkboxes, choosing from dropdowns and pressing keys. What matters more than the command names is what happens before the action: both tools check that the element is in a state where a real person could use it, and wait if it is not.

This lesson walks through the everyday actions in both tools side by side, explains the checks (called actionability), and shows why force options deserve suspicion. You will need locators first: see Locators in Playwright and Selecting Elements in Cypress.

Real versus stand-in. The Cypress (js) and Playwright (ts) code in static blocks is real and read-only: the site cannot run a browser. The runnable example is a simplified event simulator that shows which events fire and how actionability blocks a click. Real browsers dispatch more events and have subtler rules.

Clicking

A real click is not one event. The browser fires pointer and mouse events in sequence (pointerdown, mousedown, pointerup, mouseup, click), and some pages listen for the early ones. Both tools simulate the whole sequence at the element's position.

JavaScript
// Cypress
cy.get('[data-cy=save]').click();
cy.get('[data-cy=row]').first().dblclick();
cy.get('[data-cy=menu]').rightclick();
cy.get('canvas').click('topLeft');          // a named position
cy.get('canvas').click(30, 80);             // x, y from the top-left
cy.get('[data-cy=save]').click({ shiftKey: true });
TypeScript
// Playwright
await page.getByRole('button', { name: 'Save' }).click();
await page.getByTestId('row').first().dblclick();
await page.getByTestId('menu').click({ button: 'right' });
await page.locator('canvas').click({ position: { x: 30, y: 80 } });
await page.getByRole('button', { name: 'Save' }).click({ modifiers: ['Shift'] });

Typing and filling

Typing has two meanings, and the difference is a common source of confusion.

Setting the value. Playwright's fill() focuses the field, replaces its value and fires an input event. It is fast and works with most inputs. Cypress has no exact equivalent: type() always sends key events, so the closest quick form is .type('text', { delay: 0 }), and .clear() empties a field first.

Pressing keys. When the page reacts to individual keystrokes (an autocomplete, a character counter, a keyboard shortcut), you need real key events. Cypress type() does this by default and understands special sequences in braces. Playwright uses pressSequentially() for text and press() for a single key or chord.

JavaScript
// Cypress
cy.get('[data-cy=email]').clear().type('[email protected]');
cy.get('[data-cy=search]').type('espresso{enter}');
cy.get('[data-cy=notes]').type('{selectall}{backspace}');
cy.get('[data-cy=amount]').type('42', { delay: 0 });
TypeScript
// Playwright
await page.getByLabel('Email').fill('[email protected]');
await page.getByLabel('Email').clear();
await page.getByRole('searchbox').pressSequentially('espresso', { delay: 50 });
await page.getByRole('searchbox').press('Enter');
await page.keyboard.press('Control+A');   // goes to whichever element has focus

Prefer fill() unless your test is about keystrokes. A rule of thumb: if the page has a handler on keydown, keyup or keypress, press keys; if it only reads the final value, set the value.

Checkboxes, radios and selects

Checking a box with a bare click() toggles it, so running the step twice leaves it unchecked. The dedicated commands set a state instead.

JavaScript
// Cypress
cy.get('[data-cy=terms]').check();
cy.get('[data-cy=newsletter]').uncheck();
cy.get('[type=radio]').check('express');          // choose by value
cy.get('[data-cy=size]').select('Medium');        // by visible text or value
cy.get('[data-cy=size]').select(['S', 'M']);      // a multiple select
TypeScript
// Playwright
await page.getByLabel('I agree to the terms').check();
await page.getByLabel('Newsletter').uncheck();
await page.getByLabel('Express shipping').check();
await page.getByLabel('Size').selectOption('Medium');          // matches value or label
await page.getByLabel('Size').selectOption({ label: 'Medium' });
await page.getByLabel('Gift wrap').setChecked(true);

Playwright's check() also verifies that the box actually ended up checked and throws if it did not (for example because the app re-rendered it).

Hover, drag and scroll

Hover and drag are where the tools differ most.

  • Hover. Playwright has hover(), which moves the real pointer and triggers CSS :hover styles. Cypress cannot trigger real :hover, so you either force the element visible, call .trigger('mouseover') to send the events your JavaScript listens for, or add a plugin such as cypress-real-events for genuine pointer input.
  • Drag and drop. Playwright: source.dragTo(target), or page.mouse.move(), down(), up() for fine control. Cypress: send mousedown, mousemove and mouseup with .trigger(), or use a plugin; HTML5 drag-and-drop with dataTransfer often needs extra care in both tools.
  • Scrolling. Both tools scroll an element into view automatically before acting. For explicit scrolling use cy.scrollTo('bottom') and .scrollIntoView() in Cypress, or locator.scrollIntoViewIfNeeded() and page.mouse.wheel(0, 600) in Playwright, which is useful to trigger infinite scroll.
TypeScript
await page.getByRole('menuitem', { name: 'Products' }).hover();
await expect(page.getByRole('menu', { name: 'Products' })).toBeVisible();

await page.getByText('Card A').dragTo(page.getByTestId('done-column'));

await page.mouse.wheel(0, 2000);  // infinite scroll: load the next page of results

Actionability: the checks before every action

Before acting, both tools wait for the element to be usable. In outline:

flowchart TD
  A["Action requested<br/>(for example click)"] --> B["Find the element"]
  B --> C{"Attached, visible,<br/>and enabled?"}
  C -- no --> R["Wait and retry"]
  C -- yes --> D{"Stable (not animating)?"}
  D -- no --> R
  D -- yes --> E["Scroll into view"]
  E --> F{"Receives the pointer events?<br/>(nothing covering it)"}
  F -- no --> R
  F -- yes --> G["Perform the action"]
  R --> H{"Timeout reached?"}
  H -- no --> B
  H -- yes --> I["Fail with the reason"]

Both tools run a loop like this one. The exact list and the timeouts differ, but the idea is the same.

Cypress checks that the element is visible, not disabled, not detached from the DOM, not animating, not covered by another element, and, for typing, not read-only. It retries until defaultCommandTimeout (4 seconds by default). Playwright checks visible, stable, enabled and receives-events for clicks, plus editable for fill(); action waits are bounded by the test timeout (30 seconds by default) unless you set actionTimeout.

When an action cannot proceed, the error names the reason: "element is covered by another element", "element is not visible", "element is disabled". Read it. It is usually telling you something true about your app: a cookie banner really is blocking the button.

Why force is a trap

Both tools let you skip the checks:

JavaScript
cy.get('[data-cy=buy]').click({ force: true });
TypeScript
await page.getByRole('button', { name: 'Buy' }).click({ force: true });

Sometimes this is legitimate: a custom checkbox hides the native input with CSS and you must click it anyway. But most of the time force hides a real problem. If a user could not click the button because an overlay covers it, a passing test with force is lying. Before forcing, ask what is blocking the element and fix the test (dismiss the banner, wait for the animation) or the app (the overlay has a bug). Playwright's click({ trial: true }) runs the checks without clicking, which helps when debugging.

The simulator

The stand-in below models an element that can be visible, disabled or covered. Actions run a check first, then dispatch the same event sequences a browser would. fill sets the value at once; type fires keys one at a time; check looks at the current state and only clicks when needed. Run it and compare the logs.

JS Event sequences and actionability checks

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

No output.

The first section shows that a click is five events, not one. fill produces a single input event while type("hi") produces three events per character. check is idempotent: the second call clicks nothing because the box is already ticked. The covered button and the disabled button are blocked with a reason, and force pushes the click through the cover, which is exactly why it can hide a genuine defect.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main difference between Playwright's fill() and pressSequentially()?

    fill() replaces the value in one step. pressSequentially() presses each key, which matters when the page listens for keydown, keyup or per-character input.
  2. 2. Why is check() usually better than click() for a checkbox?

    A click toggles. check() looks at the current state and only acts if the box is unchecked, which makes steps repeatable.
  3. 3. A click fails with "element is covered by another element". What is the best first response?

    The message describes a real condition a user would also face. Dismissing the overlay or waiting for the animation is the fix; force merely hides the problem.
  4. 4. Which statement about hover is accurate?

    Playwright moves the real pointer. Cypress does not simulate CSS :hover, so tests send the events the page listens for or add a plugin.

Summary

  • Click, type, check, select, hover, drag and scroll exist in both tools; the names differ (fill and pressSequentially in Playwright, type in Cypress).
  • Use state-setting commands (check, uncheck, selectOption, select) rather than toggling clicks.
  • Prefer setting a value over typing keys unless the page reacts to keystrokes.
  • Before acting, both tools wait until the element is visible, enabled, stable and not covered, and they report why they gave up.
  • force skips those checks and can hide real bugs; investigate the blocker first.
  • The simulator here is a teaching model, not either tool's real implementation.

Next: Assertions That Retry.