Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 35 ยท Projects

Project: Test a Todo App

Write a maintainable test suite for a todo app in Cypress and Playwright: add, complete, filter, delete, persistence, a page object and count assertions.

A todo list is the "hello world" of web interfaces, and for a good reason: it has a little of everything. Users create items, change them, filter them, delete them, and expect the list to survive a page reload. The app has state (the items), derived values (the "items left" counter), list rendering (how many rows, in what order) and persistence. Those are exactly the things that make browser tests tricky, so this project is a compact tour of them.

You will plan the behavior, build a page object so the tests read like sentences, and write the suite in both Cypress and Playwright. As in the login project, the real tools cannot run here, so their code is read-only, and the runnable examples are stand-ins: a todo application written as plain JavaScript with a fake storage object, and tests that drive it through a page object.

The behavior to test

Write the rules first:

Area Rule
Add Typing text and pressing Enter adds an item at the end of the list; the input is cleared
Add Blank or spaces-only text is ignored
Complete Toggling an item marks it done and lowers the "items left" counter
Counter "1 item left" for one, "2 items left" for any other number (including 0)
Filter "Active" shows unfinished items, "Completed" shows finished ones, "All" shows everything
Delete Deleting removes only that item
Persist After a reload, the items and their done state are still there
Isolation A new test starts from an empty list
flowchart LR
  U["User action<br/>add / toggle / delete / filter"] --> S["App state<br/>(list of todos)"]
  S --> R["Rendered list<br/>and counter"]
  S --> P["Saved in browser storage"]
  P -->|"reload"| S

Persistence closes a loop: state is saved after every change and read back on reload, and a test should walk that loop.

The stand-in application

The app below keeps todos in an array, saves them to a storage object after every change, and loads them at start. The render() method returns the text a user would see. The fake storage has the same getItem and setItem methods as the browser's localStorage. In the demo, creating a second app on the same storage plays the role of a page reload.

JS The todo application (stand-in)

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

No output.

Check the output against the rules: the blank item was ignored, the counter dropped to 2 after completing one, the filter hid the finished one, the delete removed only #2, and the reload brought the state back from storage with the same counter.

A page object keeps tests readable

If every test repeats page.getByPlaceholder('What needs to be done?').fill(...) followed by pressing Enter, then renaming that placeholder breaks twenty tests. A page object puts the knowledge of how to talk to the page in one place, and leaves the tests with what the user does: todo.add('Buy milk'). The longer story, including when abstraction hurts, is in Page Objects and Better Test Structure.

Here is the Playwright version:

TypeScript
// tests/todo-page.ts (read-only)
import { expect, type Locator, type Page } from '@playwright/test';

export class TodoPage {
  readonly input: Locator;
  readonly items: Locator;
  readonly counter: Locator;

  constructor(private readonly page: Page) {
    this.input = page.getByPlaceholder('What needs to be done?');
    this.items = page.getByTestId('todo-item');
    this.counter = page.getByTestId('todo-count');
  }

  async goto() {
    await this.page.goto('/');
  }

  async add(text: string) {
    await this.input.fill(text);
    await this.input.press('Enter');
  }

  item(text: string): Locator {
    return this.items.filter({ hasText: text });
  }

  async toggle(text: string) {
    await this.item(text).getByRole('checkbox').check();
  }

  async remove(text: string) {
    await this.item(text).getByRole('button', { name: 'Delete' }).click();
  }

  async showFilter(name: 'All' | 'Active' | 'Completed') {
    await this.page.getByRole('link', { name }).click();
  }

  async expectTexts(texts: string[]) {
    await expect(this.items).toHaveText(texts);
  }
}

And the matching helper for Cypress. Cypress discourages large class-based page objects, because commands are queued rather than awaited, so a plain object of small functions that return the chain is the idiomatic form:

JavaScript
// cypress/support/todo-page.js (read-only)
export const todo = {
  visit: () => cy.visit('/'),
  add: (text) => cy.get('[data-cy=new-todo]').type(`${text}{enter}`),
  items: () => cy.get('[data-cy=todo-item]'),
  item: (text) => cy.contains('[data-cy=todo-item]', text),
  toggle: (text) => todo.item(text).find('input[type=checkbox]').check(),
  remove: (text) => todo.item(text).find('button[aria-label=Delete]').click(),
  showFilter: (name) => cy.contains('a', name).click(),
}

In this layout the delete button must be present in the DOM and visible at all times (or at least when the row is hovered by CSS). Cypress cannot trigger a CSS :hover state, so a button that only appears on hover needs a different strategy, such as click({ force: true }) or giving the button a visible state in the test environment. Keeping a test-friendly delete control is a design decision you can make together with the developers.

The tests

Now the suite. Notice how little the tests know about the page.

TypeScript
// tests/todo.spec.ts (read-only)
import { test, expect } from '@playwright/test';
import { TodoPage } from './todo-page';

test.describe('todo list', () => {
  let todo: TodoPage;

  test.beforeEach(async ({ page }) => {
    todo = new TodoPage(page);
    await todo.goto();
  });

  test('adds items in order and clears the input', async () => {
    await todo.add('Buy milk');
    await todo.add('Walk the dog');
    await todo.expectTexts(['Buy milk', 'Walk the dog']);
    await expect(todo.input).toBeEmpty();
  });

  test('ignores blank input', async () => {
    await todo.add('   ');
    await expect(todo.items).toHaveCount(0);
  });

  test('counts items left with correct wording', async () => {
    await todo.add('One');
    await expect(todo.counter).toHaveText('1 item left');
    await todo.add('Two');
    await expect(todo.counter).toHaveText('2 items left');
    await todo.toggle('One');
    await expect(todo.counter).toHaveText('1 item left');
    await todo.toggle('Two');
    await expect(todo.counter).toHaveText('0 items left');
  });

  test('filters active and completed', async () => {
    await todo.add('Done thing');
    await todo.add('Open thing');
    await todo.toggle('Done thing');

    await todo.showFilter('Active');
    await todo.expectTexts(['Open thing']);
    await todo.showFilter('Completed');
    await todo.expectTexts(['Done thing']);
    await todo.showFilter('All');
    await expect(todo.items).toHaveCount(2);
  });

  test('deletes only the chosen item', async () => {
    await todo.add('Keep');
    await todo.add('Remove');
    await todo.remove('Remove');
    await todo.expectTexts(['Keep']);
  });

  test('keeps items and done state after a reload', async ({ page }) => {
    await todo.add('Persistent');
    await todo.toggle('Persistent');
    await page.reload();
    await expect(todo.item('Persistent').getByRole('checkbox')).toBeChecked();
    await expect(todo.counter).toHaveText('0 items left');
  });
});

The Cypress spec reads almost the same:

JavaScript
// cypress/e2e/todo.cy.js (read-only)
import { todo } from '../support/todo-page'

describe('todo list', () => {
  beforeEach(() => {
    todo.visit()
  })

  it('adds items in order and clears the input', () => {
    todo.add('Buy milk')
    todo.add('Walk the dog')
    todo.items().should('have.length', 2)
    todo.items().first().should('contain.text', 'Buy milk')
    todo.items().last().should('contain.text', 'Walk the dog')
    cy.get('[data-cy=new-todo]').should('have.value', '')
  })

  it('counts items left with correct wording', () => {
    todo.add('One')
    cy.get('[data-cy=todo-count]').should('have.text', '1 item left')
    todo.add('Two')
    cy.get('[data-cy=todo-count]').should('have.text', '2 items left')
    todo.toggle('One')
    cy.get('[data-cy=todo-count]').should('have.text', '1 item left')
  })

  it('keeps items and done state after a reload', () => {
    todo.add('Persistent')
    todo.toggle('Persistent')
    cy.reload()
    todo.item('Persistent').find('input[type=checkbox]').should('be.checked')
    cy.get('[data-cy=todo-count]').should('have.text', '0 items left')
  })
})

Three habits in these tests deserve a spotlight:

  • Assert on counts and lists, not on single rows. toHaveCount(0) and toHaveText([...]) (or should('have.length', n)) check the whole list, so a stray extra row or a wrong order fails the test. Both retry until the list settles, as explained in Assertions That Retry.
  • Find items by their text, not their position. item('Remove') still works if the list is sorted differently or a new row is added above it.
  • Start every test empty. Playwright gives each test a fresh browser context, and Cypress clears local storage between tests, so a leftover item cannot leak. The persistence test reloads inside one test, which is the only place state should carry over.

Running the plan against the stand-in

Finally, the same structure on the stand-in: a page object that finds items by text, the six test ideas above, and a tiny runner. The app code is a compact copy so the example runs on its own. Notice the last test, which is meant to fail: it shows what an assertion message on a list looks like.

JS Page object and tests on the stand-in

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

No output.

All tests pass except the deliberate one, and its message shows both lists in full. The last line of defense for a list test is always a message like that: expected versus actual, with both complete. That is why asserting the whole list beats checking one row.

Where to go from here

Extend the project with these ideas:

  • An edit feature (double-click an item, change the text, press Enter or Escape).
  • A "Clear completed" button, plus a test that it hides itself when nothing is done.
  • A "toggle all" checkbox, which is a good test of derived state.
  • Replace the UI setup in the persistence test with direct storage seeding (Playwright's page.addInitScript, or Cypress cy.window().then(win => win.localStorage.setItem(...))) to start from a known list without typing.
  • Check the whole page with an accessibility scan, as in Visual and Accessibility Testing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of a page object in this project?

    When the page changes, you update the page object once instead of editing every test.
  2. 2. Why is toHaveText(['Keep']) or should('have.length', n) on the whole list better than checking one row?

    Whole-list assertions verify the complete result and give a full expected-versus-actual message.
  3. 3. Where is state allowed to carry over within a single test in this suite?

    Each test starts clean. Persistence is the one feature that is about state surviving a reload, so that test reloads inside itself.
  4. 4. Why find an item by its text rather than by its index?

    Position is an accident of the current layout; the item's text is the user-visible identity.

Summary

  • Write the rules of the feature as a table, then turn each rule into a test.
  • A todo app exercises list rendering, derived values (the counter), filters, deletion and persistence.
  • A page object (a class in Playwright, a plain object of chain-returning functions in Cypress) makes tests read as user actions.
  • Assert on whole lists and counts, find items by text, and keep every test independent with a fresh state.
  • Test persistence by reloading inside one test.

Next: Project: Test a Shopping Cart and Checkout