Calmcode - playwright: testing search

Codegen is not always enough

1 2 3 4 5 6 7 8 9

In this section we are using codegen to construct a test, but it will fail when you run it. Here's the test in question.

from playwright.sync_api import Page, expect


def test_search(page: Page) -> None:
    page.goto("/")
    page.get_by_role("link", name="Search").click()
    page.get_by_placeholder("Search calmcode content").click()
    page.get_by_placeholder("Search calmcode content").fill("pur")
    page.get_by_role("link", name="pur.py").click(timeout=1000)
    page.get_by_text("pur.py").click()

The issue in this case is that the .fill() action is filling in the text way too fast. So fast that the response can't render yet. It serves as a nice example that codegen won't always generate perfect code for you.

Solution 1: An extra event

One way around this is to add an extra keypress event after the fill. Something like this:

from playwright.sync_api import Page, expect


def test_search(page: Page) -> None:
    page.goto("/")
    page.get_by_role("link", name="Search").click()
    page.get_by_placeholder("Search calmcode content").click()
    page.get_by_placeholder("Search calmcode content").fill("pur")
    page.get_by_placeholder("Search calmcode content").press("Enter")
    page.get_by_role("link", name="pur.py").click(timeout=1000)
    page.get_by_text("pur.py").click()

Solution 2: Better interaction

Instead of using the .fill() action, which dumps all the text in one go, you may also consider using the type() action.

from playwright.sync_api import Page, expect


def test_search(page: Page) -> None:
    page.goto("/")
    page.get_by_role("link", name="Search").click()
    page.get_by_placeholder("Search calmcode content").click()
    page.get_by_placeholder("Search calmcode content").type("pur", delay=150)
    page.get_by_role("link", name="pur.py").click(timeout=1000)
    page.get_by_text("pur.py").click()

There are pros and cons here. On one hand the typing action feels nicer because it mimics the user more closely. However, the delay of typing will also make the test a fair bit slower.