Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 35 ยท Practice and Review

Exercises with Solutions

Twelve graded exercises on selectors, assertions, intercepts, structure and flaky tests, each with a worked solution and runnable logic checks.

Reading about browser testing teaches you the vocabulary. Writing tests, and fixing broken ones, teaches you the craft. This lesson gives you twelve exercises, graded from easy to hard. Each one states a task, then a solution. Try the task first, even on paper, before you read the solution.

Cypress and Playwright cannot run on this site, so the exercises and solutions are read-only code for a made-up application. Three of the exercises have a runnable stand-in in plain JavaScript that checks the logic behind the answer. Use them to experiment: change the numbers and see what happens.

The exercises refer to ideas from earlier lessons. If one feels unfamiliar, the link in its heading takes you back.

flowchart TD
  A["Test fails"] --> B{"Fails every time?"}
  B -->|"yes"| C["Read the error:<br/>selector, assertion or app bug"]
  B -->|"no, sometimes"| D{"Depends on timing?"}
  D -->|"yes"| E["Wait for a condition,<br/>not for a duration"]
  D -->|"no"| F["Look for shared state<br/>or unstable data"]

A quick triage for the failing and flaky tests in exercises 6, 7, 10 and 11.

Level 1: warm-ups

Exercise 1: choose the best selector

The page contains <button class="btn btn-primary mt-2" id="b7" data-testid="save">Save changes</button>. Which locator would you use in Playwright, and which in Cypress? Rank the four options: the class, the id b7, the test id, and the role with its name. Related lesson: Writing Selectors That Do Not Break.

Solution. Prefer what a user can perceive first. In Playwright, page.getByRole('button', { name: 'Save changes' }) is the best choice, because it also proves the control is exposed as a button with a sensible name. The test id getByTestId('save') is second: stable, but invisible to users. The id b7 is third, since generated-looking ids change. The class is last because classes are styling, and they change for visual reasons. In Cypress, cy.contains('button', 'Save changes') plays the role of the first choice and cy.get('[data-cy=save]') the second. Use the test id when the visible text changes often (for example, translated text).

Exercise 2: your first assertion

Write a test that opens /about and checks that the main heading says "About us". Do it in both tools.

Solution.

TypeScript
// Playwright (read-only)
import { test, expect } from '@playwright/test';

test('about page has a heading', async ({ page }) => {
  await page.goto('/about');
  await expect(page.getByRole('heading', { level: 1 })).toHaveText('About us');
});
JavaScript
// Cypress (read-only)
it('about page has a heading', () => {
  cy.visit('/about')
  cy.get('h1').should('have.text', 'About us')
})

Both assertions retry until they pass or time out, so there is no need for a manual wait.

Exercise 3: this assertion does not retry

A teammate wrote this Cypress test and it fails once a month:

JavaScript
cy.get('[data-cy=count]').then(($el) => {
  expect($el.text()).to.eq('3 items')
})

Why? Fix it. Related lesson: Assertions That Retry.

Solution. Inside .then() the callback runs once with whatever the element looked like at that moment. If the count updates a moment later, the assertion fails and nothing retries it. Move the assertion into the chain:

JavaScript
cy.get('[data-cy=count]').should('have.text', '3 items')

A .should() retries the whole query and assertion until it passes. If you really need a callback, put the assertions inside .should(($el) => { ... }), which retries too.

Exercise 4: act inside the right row

A table lists three people, and every row has a Delete button. Write a locator that deletes only Grace's row, then run the stand-in to see why an unscoped locator is a problem. Related lessons: Locators in Playwright and Selecting Elements in Cypress.

Solution.

TypeScript
// Playwright (read-only)
await page
  .getByRole('row', { name: /Grace/ })
  .getByRole('button', { name: 'Delete' })
  .click();
JavaScript
// Cypress (read-only)
cy.contains('tr', 'Grace').within(() => {
  cy.contains('button', 'Delete').click()
})

The unscoped getByRole('button', { name: 'Delete' }) matches three buttons. Playwright is strict: it throws instead of guessing, and that is a feature. The stand-in models the same rule.

JS Strict matching and row scoping

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

No output.

Level 2: everyday skills

Exercise 5: stub a user profile

The page calls GET /api/me and shows Hello, <name>. Stub the response so the test controls the name, and assert the greeting. Related lesson: Intercepting and Mocking Network Requests.

Solution.

TypeScript
// Playwright (read-only)
test('greets the user', async ({ page }) => {
  await page.route('**/api/me', (route) =>
    route.fulfill({ json: { name: 'Mina' } }),
  );
  await page.goto('/');
  await expect(page.getByTestId('greeting')).toHaveText('Hello, Mina');
});
JavaScript
// Cypress (read-only)
it('greets the user', () => {
  cy.intercept('GET', '/api/me', { body: { name: 'Mina' } }).as('me')
  cy.visit('/')
  cy.wait('@me')
  cy.get('[data-cy=greeting]').should('have.text', 'Hello, Mina')
})

The stub is registered before navigation. Registering it afterwards is the most common mistake in this exercise.

Exercise 6: replace the fixed sleep

This test passes on a developer laptop and fails in CI:

JavaScript
cy.contains('button', 'Save').click()
cy.wait(500)
cy.get('[data-cy=toast]').should('be.visible')

The Playwright version has await page.waitForTimeout(500) in the same place. Explain the problem and fix both. Then use the stand-in to compare a fixed wait with a condition wait. Related lesson: Auto-Waiting in Playwright.

Solution. A fixed pause guesses how long the app takes. On a fast machine it wastes time; on a slow one it is too short and the test fails. Delete the pause: the assertion already waits. If you need to be sure the save finished, wait for the response the save triggers.

JavaScript
// Cypress (read-only)
cy.intercept('POST', '/api/save').as('save')
cy.contains('button', 'Save').click()
cy.wait('@save')
cy.get('[data-cy=toast]').should('be.visible')
TypeScript
// Playwright (read-only)
await page.getByRole('button', { name: 'Save' }).click();
await expect(page.getByTestId('toast')).toBeVisible();
JS Fixed sleep versus polling for a condition

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

No output.

The polling version waits only as long as needed, passes on the slow server, and still fails (after its limit) when the app is truly broken.

Exercise 7: the variable that stays empty

JavaScript
const price = cy.get('[data-cy=price]').invoke('text')
cy.get('[data-cy=total]').should('contain', price)

The test fails with a strange message. Why, and how do you fix it? Related lesson: How Cypress Commands Really Work.

Solution. Cypress commands do not return values; they queue work and yield results to the next command. price is a chain object, not text. Use .then() to receive the value, or an alias:

JavaScript
cy.get('[data-cy=price]').invoke('text').then((price) => {
  cy.get('[data-cy=total]').should('contain', price.trim())
})

In Playwright you would not have this problem, because await locator.textContent() returns the string directly.

Exercise 8: test form validation

A sign-up form has these rules: the email must contain @, the password must have at least 8 characters, and "Confirm" must equal the password. Write a data-driven test with five cases, then check the cases against the stand-in. Related lesson: Forms, Uploads and Downloads.

Solution. One test body, many rows of data:

TypeScript
// Playwright (read-only)
const cases = [
  { email: 'ada.example.com', password: 'longenough', confirm: 'longenough', error: 'Enter a valid email' },
  { email: '[email protected]', password: 'short',      confirm: 'short',      error: 'Use at least 8 characters' },
  { email: '[email protected]', password: 'longenough', confirm: 'different',  error: 'Passwords do not match' },
];

for (const c of cases) {
  test(`rejects ${c.error}`, async ({ page }) => {
    await page.goto('/signup');
    await page.getByLabel('Email').fill(c.email);
    await page.getByLabel('Password', { exact: true }).fill(c.password);
    await page.getByLabel('Confirm').fill(c.confirm);
    await page.getByRole('button', { name: 'Create account' }).click();
    await expect(page.getByRole('alert')).toHaveText(c.error);
  });
}
JS The rules behind the validation test

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

No output.

The last case raises a design question for the page: does it show all errors at once or only the first? Pick one, then make the browser test match it.

Level 3: design and debugging

Exercise 9: tidy up a test file

You inherit a file where twelve tests each start with the same eight lines of login steps and use #u and #p selectors. List the changes you would make, in order. Related lessons: Page Objects and Better Test Structure and Hooks, Fixtures and Custom Commands.

Solution. In order of payoff:

  1. Replace the repeated login steps with a login by API and a reused session (cy.session or Playwright's storageState), keeping a single test that logs in through the form.
  2. Move the shared setup into beforeEach or a fixture, so the twelve tests state only what is different.
  3. Replace #u and #p with label-based or test-id locators, in one page object.
  4. Rename tests so each reads as a sentence about behavior ("rejects an expired card").
  5. Leave assertions in the tests; do not hide them in helpers.

Exercise 10: a test that fails only when run in parallel

test A creates a note called "Draft" and expects the list to contain exactly one note. test B does the same. Alone, each passes; together, they fail about half the time. Find the cause and give two fixes. Related lesson: Finding and Fixing Flaky Tests.

Solution. The tests share state: both write to the same account, so each sees the other's note. Fixes: (1) give each test its own data (a unique user or a uniquely named note, and assert on that note rather than on the total count); (2) seed and clean up through the API per test. Avoid the weak fixes, such as running everything serially, which hides the coupling and makes the suite slow.

Exercise 11: test a slow and a failing server

The page loads a list from GET /api/items. Write two tests: one where the response takes three seconds and the page must show a loading indicator, and one where the request fails and the page must show an error.

Solution.

TypeScript
// Playwright (read-only)
test('shows a spinner while loading', async ({ page }) => {
  await page.route('**/api/items', async (route) => {
    await new Promise((r) => setTimeout(r, 3000));
    await route.fulfill({ json: [] });
  });
  await page.goto('/items');
  await expect(page.getByRole('progressbar')).toBeVisible();
});

test('shows an error when the request fails', async ({ page }) => {
  await page.route('**/api/items', (route) => route.abort('failed'));
  await page.goto('/items');
  await expect(page.getByRole('alert')).toContainText('Something went wrong');
});
JavaScript
// Cypress (read-only)
it('shows a spinner while loading', () => {
  cy.intercept('GET', '/api/items', { body: [], delay: 3000 })
  cy.visit('/items')
  cy.get('[role=progressbar]').should('be.visible')
})

it('shows an error when the request fails', () => {
  cy.intercept('GET', '/api/items', { forceNetworkError: true })
  cy.visit('/items')
  cy.get('[role=alert]').should('contain', 'Something went wrong')
})

Keep the artificial delay as short as the test needs. Three seconds is for illustration; a delay just long enough for the spinner assertion to see it is enough.

Exercise 12: decide what belongs in the browser

You have eight candidate tests for a checkout. Pick the ones to write as browser tests and say where the others belong: (a) a coupon adds the right discount for 40 inputs; (b) a stubbed payment error shows a message; (c) a full purchase from catalog to confirmation; (d) the tax function rounds correctly; (e) the Pay button is disabled while the request is in flight; (f) the address form requires a postal code; (g) the order email contains the order number; (h) the "Place order" button has the right color. Related lesson: Testing Strategy and the Test Pyramid.

Solution. Browser tests: (b), (c), (e), (f), because they are about what the user sees and does. Unit tests: (a) and (d), which are pure calculations with many inputs. (g) is an integration test of the mail code (check the generated message, not a browser). (h) is a visual or design check, best handled by a visual-regression test or left to review, not a functional assertion. In the browser suite keep (c) as the single long journey and make (b), (e) and (f) short tests with stubbed or seeded data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Cypress test uses cy.get('x').then(($el) => expect($el.text()).to.eq('3 items')) and fails occasionally. What is the best fix?

    A callback in then() runs once. A should() assertion retries the query and the check until they pass or time out.
  2. 2. Why is a fixed sleep a poor way to wait for a toast message?

    A condition-based wait takes as long as the app needs. A fixed duration is a guess that will eventually be wrong.
  3. 3. An unscoped getByRole('button', { name: 'Delete' }) matches three buttons. What does Playwright do when you click it?

    Locators are strict by default for actions. Scope the locator to a row, or use filter, first or nth on purpose.
  4. 4. Which tests of a checkout fit best in the browser suite?

    Browser tests are for visible behavior and wiring. Pure calculations and email content belong in cheaper test layers.
  5. 5. Two tests pass alone but fail together in parallel. What is the most likely cause?

    Tests that touch the same data depend on each other's timing. Give each test its own data.

Summary

  • Prefer role, label or test-id locators, and scope them to the row or region you mean.
  • Put assertions in the retrying form (should, expect(locator)), never in a one-shot callback.
  • Wait for a condition or a network response, never a fixed duration.
  • Stub before you navigate, and cover slow and failing responses on purpose.
  • Cypress variables hold chains, not values; use .then() or aliases.
  • Fix flaky parallel failures by isolating data, not by serializing the suite.
  • Use the browser for visible behavior; keep calculations and message content in cheaper layers.

Next: Interview Questions