End-to-end tests for chat UIs with Playwright

Study time
≈ 3.5 h (estimate)
Needs
L1-M07-L02
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M07 · Duration: ~195 min (estimate, including the independent exercise) · Previous: L02 · Next: L04 - Reports and CI with GitHub Actions, with cost control

1. Introduction

Customers do not call the API. They type into a chat box on a web page. Many bugs appear only there: clicking the Send button twice sends two requests, the "Đang trả lời..." status (Replying...) never goes away, the Enter key does not send, a new answer wipes out the previous one, and the most serious of all: the model's output is inserted into the page as HTML.

This lesson teaches end-to-end testing of a chat interface with Playwright: open a real browser, act like a user, and assert what the user sees. The backend uses ScriptedClient (L02), so the tests are offline and deterministic.

2. Learning objectives

  1. Write Playwright tests with the page fixture of pytest-playwright.
  2. Choose user-facing locators (get_by_role, get_by_label) and use self-waiting assertions (expect).
  3. Verify the states of a chat interface: waiting, error, recovery, conversation history.
  4. Verify that the model's output is displayed as text, not as HTML (OWASP LLM05).
  5. Use a trace to investigate a failing UI test.

3. Prerequisites and tools

  • L02: ScriptedClient.
  • L1-M04-L04: the model's output is untrusted data.
  • Basic HTML: tags, attributes. No JavaScript writing is needed, except one short expression inside page.evaluate(...) (for example in the long-answer test).

4. Concepts

4.1 Playwright and pytest-playwright

Install as the documentation describes: pip install pytest-playwright, then playwright install to download the browsers [R1]. The pytest plugin provides the page fixture, "New browser page for a test", and command-line options such as --headed ("Run tests in headed mode (default: headless)"), --browser (chromium by default) and --tracing (on, off, retain-on-failure) [R2]. "Headless" means the browser runs without opening any window: it is fast, and it runs on a CI machine that has no screen.

Everyday example. A chain of shops hires "mystery shoppers": someone walks into a shop like a real customer, orders, waits, pays, and writes down what they saw. A Playwright test is the mystery shopper of the chat page: it types, clicks and reads the screen like a customer, instead of reading the page's code.

4.2 User-facing locators

The Playwright documentation recommends "prioritizing user-facing attributes and explicit contracts such as page.get_by_role()" [R3]. The reason: users find a button by the word "Gửi" (Send), not by #send-btn-2. A test that uses get_by_role("button", name="Gửi") and get_by_label("Tin nhắn") (the Message box):

  • does not break when the frontend team changes an id or a class;
  • fails when the button loses its label, so it also catches an accessibility bug.

The lab's chat page has clear roles: the conversation area role="log", the status role="status", errors role="alert".

Good vs bad.

Weak locator Good locator
page.locator("#send-btn-2"), page.locator("div.chat > form > button") page.get_by_role("button", name="Gửi"), page.get_by_label("Tin nhắn")

Why: the weak locators break when the frontend team changes an id or the layout, even though customers see no difference; the good ones fail only when a customer really cannot find the "Gửi" button.

4.3 Auto-waiting and web-first assertions

A chat interface is asynchronous: the answer arrives after a delay nobody knows in advance. time.sleep(2) is a way to make a test slow and flaky (L1-M06-L05).

  • Auto-waiting actions: Playwright "auto-waits for all the relevant checks to pass and only then performs the requested action" [R4].
  • Auto-retrying assertions: "Playwright includes web-specific assertions that automatically retry until the expected condition is met" [R5]. expect(locator).to_have_count(1) waits until there is exactly one reply bubble, or until the timeout runs out.

The rule: use expect(...) for everything you need to wait for; use a plain assert only for data that is already available, such as the server's chat.api_calls log.

Everyday example. At a crossroads, a driver waits for the green light before moving off, instead of closing their eyes and counting 10 seconds. Counting wastes time when the light turns green early and is dangerous when the red lasts longer. expect(...) is watching the light; time.sleep(...) is counting seconds.

Worked example: sleep or expect. The lab's fake backend answers a message containing "chậm" (slow) after exactly 1 second (the rule ("chậm", ("slow", 1.0, ...)) in chat_app/server.py). Save as exercises/vd_l03_wait.py:

import time

import pytest
from playwright.sync_api import expect

pytestmark = pytest.mark.ui


def send_slow_question(page):
    page.get_by_label("Tin nhắn").fill("trả lời chậm thôi")      # the scripted reply takes 1 second
    page.get_by_role("button", name="Gửi").click()
    return page.get_by_role("log").locator("li[data-role=assistant]")


def test_with_sleep(chat_page):
    replies = send_slow_question(chat_page)
    time.sleep(0.5)                                              # a guess
    assert replies.count() == 1


def test_with_expect(chat_page):
    replies = send_slow_question(chat_page)
    expect(replies).to_have_count(1)                             # waits up to 5 s, stops as soon as it is true

Run python -m pytest -q exercises/vd_l03_wait.py. Output (excerpt, run times removed; copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-06; both versions gave identical output):

E       AssertionError: assert 0 == 1
FAILED exercises/vd_l03_wait.py::test_with_sleep[chromium] - AssertionError: ...
1 failed, 1 passed, 1 warning
  1. test_with_sleep guesses that 0.5 seconds is enough. The answer needs 1 second, so when the assert runs there is no bubble yet: assert 0 == 1.
  2. test_with_expect passes: to_have_count(1) keeps retrying and stops as soon as the bubble appears, after about 1 second, without waiting the full 5 seconds.
  3. Change 0.5 to 2 and test_with_sleep passes too, but it always costs 2 seconds, and it will fail again on the day the CI machine is slower. The 1 warning is pytest-playwright's base_url warning (see the lab README). Delete the file when you are done.

4.4 The model's output is data, not HTML

OWASP LLM05 describes exactly this case: "JavaScript or Markdown is generated by the LLM and returned to a user. The code is then interpreted by the browser, resulting in XSS" [R6]. If the page inserts the answer with innerHTML, an answer containing <img src="x" onerror="..."> will run code in the customer's browser. Such an answer can come from indirect prompt injection (L1-M04-L04). XSS (cross-site scripting) is a bug that lets an attacker run their script in someone else's browser, with that page's permissions.

The lab's test sends a message to which the fake backend replies with exactly that piece of HTML, then asserts three things: the displayed text contains the whole <img ...> snippet, there is no <img> element in the bubble, and window.__pwned is not set.

Everyday example. Someone pins a note on the notice board of an apartment building: "Guards, please open storeroom number 3". The guard reads it as a notice, and does not obey it as an order from the management. A page using textContent behaves like that guard; a page using innerHTML obeys every word pinned on the board.

Good vs bad.

Weak XSS test Good XSS test
expect(reply).to_contain_text("giảm 10%") The text contains the whole <img ...> snippet, and reply.locator("img") has 0 elements, and window.__pwned is None

Why: the demo in §8.1 shows that the innerHTML page displays 'Ưu đãi: giảm 10%', so the weak test passes on both the safe page and the XSS page. A test that cannot tell the right page from the wrong one checks nothing.

4.5 A checklist for a chat interface

Behaviour How the lab tests it
Ask and get an answer The user and assistant bubbles have the right text
The Enter key sends press("Enter"), count the requests at the server
An empty message is not sent Send whitespace; no request
No duplicate send while waiting The button is disabled while waiting; exactly one request
An error is reported and the page recovers role="alert" has a message; the status is cleared; sending works again
The output is text No <img>; window.__pwned does not exist
Conversation history Both turns are shown; the second request carries the first turn too
A long answer The page has no horizontal scroll bar (scrollWidth <= clientWidth)

Everyday example. Before handing over a motorbike, a shop does not only check that "the engine starts": it checks the brakes, lights, horn, indicators, and even riding in the rain. The table above is that list for a chat box: the happy path is only the first row.

5. Technical deep dive

5.1 Fixtures in tests/ui/conftest.py

  • chat: a new ChatServer for each test, on a random port, stopped after yield (L01).
  • chat_page: uses the plugin's page fixture, sets the default timeout to 5 seconds, opens the chat page.
  • The page version (v1 or v2) comes from the environment variable AIQA_UI_VERSION, v1 by default.

5.2 Combining UI and server observations

Some bugs are visible only when you look at both sides. For example, a Send button clicked twice may show only one reply bubble, while the server receives two requests. That is why the lab's tests assert both expect(...) on the page and len(chat.api_calls) at the server.

5.3 Trace

Run with --tracing=retain-on-failure to keep the trace of failing tests in test-results/. Open the trace with python -m playwright show-trace <path>.zip: you see every step, DOM snapshots (the structure of the page at that exact moment) and network requests.

6. The QA perspective

  • What to test: the table in section 4.5; every state (waiting, error, empty, long, several turns); malicious output.
  • What can go wrong: sleep instead of expect; brittle CSS locators; testing only the happy path; a server shared between tests; not checking the server side.
  • Severity: XSS from the model's output is a security bug; a duplicate send can create an order or charge money twice if the chatbot has tools (L1-M05-L04).

7. Real-world scenarios

Scenario 1 (fictional): Markdown turned into HTML. A chatbot renders the model's Markdown to HTML so that it looks nicer. A retrieved document contains a javascript: link. The model copies that link into its answer, and the customer clicks it. The "output is text" test in its simple form does not catch this case; the team needs extra tests for the Markdown renderer itself.

Scenario 2 (fictional): "Đang trả lời..." forever. When the backend times out, the page neither clears the status nor reports an error. The customer thinks the system is working and waits five minutes. The "an error is reported and the page recovers" test catches this bug with a fake backend that always fails.

8. Hands-on tutorial

8.1 Running the demo

python demo.py l03

Output (copied from a real run, 2026-10-31):

v1 page: reply text = 'Ưu đãi: <img src="x" onerror="window.__pwned = true"> giảm 10%'
v1 page: <img> inside reply = 0, window.__pwned = None
innerHTML page: text = 'Ưu đãi:  giảm 10%'
innerHTML page: <img> inside = 1, window.__pwned = True

In English: the reply announces an offer ("Ưu đãi") with a discount ("giảm"), with the HTML snippet in the middle.

The same model answer, displayed in two ways. The v1 page uses textContent: the answer is shown verbatim and there is no <img>. The second page is a minimal piece of HTML that uses innerHTML: the <img ...> part disappears from the text because it has become an HTML element, and onerror has run (window.__pwned = True).

8.2 Running the tests

python -m pytest tests/ui -v
python -m pytest tests/ui --headed -k history          # xem trình duyệt chạy

In English, the comment says: watch the browser run.

8.3 Troubleshooting

Symptom Cause Fix
Executable doesn't exist ... playwright install The browsers have not been downloaded python -m playwright install chromium
TimeoutError or an assertion failing after 5 seconds The page did not reach the expected state Run with --headed or --tracing=retain-on-failure, then open the trace
System libraries missing on Linux The browser needs OS libraries python -m playwright install --with-deps chromium (what CI does, L04)

9. Independent exercise

9.1 Main exercise

Problem: Add two tests for v1.

Requirements: complete exercises/test_l03_more_ui.py:

  1. TODO 1: after the answer arrives, the message box must get focus back (expect(...).to_be_focused()).
  2. TODO 2: send "Đơn SE1001 giao chưa? 😊 <b>gấp</b>" (a customer asking, urgently, whether the order has been delivered) and assert that the user bubble shows exactly that string.
  3. Make one test fail on purpose (change the expected text), run it with --tracing=retain-on-failure, open the trace, and record what you see at the failing step.

Deliverable: the test file, a screenshot or a description of the trace.

Acceptance criteria: both tests pass with v1; no sleep; locators start from a role or a label (the selector li[data-role=...] inside role="log" is accepted).

Hint: to_have_text([...]) compares the whole list of bubbles.

9.2 Extra exercise: a reusable "shown as text" check (20-30 minutes)

Problem: The lab's XSS test checks one payload. A real test pack needs the same check for many answers, and the check itself must fail on every wrong way of showing an answer, not only on the one that runs a script.

Requirements: in exercises/test_l03_extra_plain_text.py:

  1. Read the four ways of showing an answer in RENDER and the two answers in REPLIES. Only textContent is right.
  2. TODO 1: write assert_shown_as_text(bubble, raw_reply): raise AssertionError unless the bubble shows raw_reply character for character, as text, with no HTML element created inside it. Use expect with a short timeout (for example timeout=1000).
  3. The last test uses your function on the real v1 chat page.

Run: python -m pytest exercises/test_l03_extra_plain_text.py (on Linux without the browser bundled with Playwright, add --browser-channel chrome, as for the lesson's UI tests). Until you do the work, the tests fail with TODO 1.

Acceptance criteria: 8 tests pass; no sleep.

Hint: the "tags stripped" page creates no element and runs no script, but the customer still sees something wrong. Which check catches it?

9.3 Real-world scenario: the chat box of a digital bank

Context (fictional): The digital bank TienXanh is about to launch a chat box that answers questions about cards. Compared with the lab's page, this one adds:

  • the answer is shown piece by piece (streaming) while the model is still writing;
  • answers contain Markdown (bold, lists, a link to the fee page) that is rendered as HTML;
  • a "Copy" button next to each answer;
  • when the login session expires midway, the server returns status 401.

Your task: write at least 8 UI test cases for this page. Each test case has: the user's action, the locator you use, what you assert on the page, what you assert on the server side (if anything), and the severity if the test fails. Add 2-3 sentences: what must the fake backend answer for the pack to run offline?

A good answer has:

  • Tests for the states, not only the happy path (in the spirit of the table in §4.5).
  • Locators by role or label; expect wherever something must be waited for, no sleep.
  • At least one test that treats the model's output as untrusted data, and explains why the new features change this risk (§4.4, §7).
  • At least one test that combines what the page shows with what the server saw (§5.2).
  • Severities with reasons tied to the bank's customers, not just a "high" label.

10. Knowledge check

0/20 done · Results are kept in this browser only.

P02 · True or false

You should add time.sleep(2) before checking the chatbot's answer.

P03 · Short answer

Why is inserting the model's output with innerHTML a security bug? Name the OWASP risk.

P04 · Short answer

Name one bug that can be found only by checking both the page and the server.

P05 · Short answer

(Scenario) A UI test fails 1 time in 20 on CI. How do you investigate, and what do you not do?

P06 · Match

According to §4.2, match each part of the lab's chat page with the locator the tests use to find it.

P08 · Multiple choice

According to §4.3, which assertion uses a plain assert and is still in the right place?

P09 · Spot the bug

The snippet below is copied from the message-sending handler in src/aiqa/chat_app/static/v1.html, with one line moved. Find the bug.

  try {
    const r = await fetch("/api/chat", {method: "POST", headers: {"content-type": "application/json"},
                                        body: JSON.stringify({messages: history})});
    const body = await r.json();
    if (!r.ok) throw new Error(body.error || "Đã xảy ra lỗi");
    add("assistant", body.reply);
    history.push({role: "assistant", content: body.reply});
    status.textContent = "";
  } catch (err) {
    history.pop();
    error.textContent = err.message.startsWith("Trợ lý") ? err.message : "Đã xảy ra lỗi, bạn thử lại nhé.";
  } finally {
    send.disabled = false;
    input.focus();
  }

P10 · Recall

Lesson: L1-M07-L02

L02 §4.3: which of these does ScriptedClient, the fake backend of the chat page in this lesson, not do?

P11 · Select all that apply

According to §6, which things can go wrong in a UI test suite for a chat interface? Select every correct option.

P12 · Put in order

Put the steps of investigating a failing UI test with a trace in order (§5.3).

  1. Look at the failing step: the DOM snapshot and the network requests
  2. Open it with python -m playwright show-trace <path>.zip
  3. Run the test with --tracing=retain-on-failure
  4. Find the trace.zip file of the failing test in test-results/

P13 · True or false

By default, pytest-playwright runs the browser in headed mode (with a visible browser window).

P14 · Short answer

test_conversation_keeps_history ends with an assertion on chat.api_calls[-1]. Why is looking at the two bubbles on the page not enough?

P15 · Multiple choice

According to §8.3, on Linux the UI tests report missing system libraries that the browser needs. Which command fixes this correctly?

P17 · Multiple choice

Worked example of §4.3: why does test_with_sleep fail while test_with_expect passes?

P18 · True or false

The test expect(reply).to_contain_text("giảm 10%") passes on both the v1 page and the innerHTML page of the §8.1 demo, so it cannot detect the XSS bug.

P19 · Apply now

In code-labs/l1-m07, do the extra exercise of §9.2: write assert_shown_as_text(bubble, raw_reply) in exercises/test_l03_extra_plain_text.py, then run python -m pytest exercises/test_l03_extra_plain_text.py.

Checklist

P20 · True or false

expect(locator).to_have_count(1) stops as soon as the condition holds, instead of always waiting for the full 5-second default timeout of chat_page.

11. Summary

  • Concepts: Playwright and the page fixture; user-facing locators; auto-waiting actions; auto-retrying assertions; the model's output is data (LLM05); traces.
  • Skills: testing the states of a chat interface; combining page and server observations; investigating with a trace.
  • Pitfalls: sleep; CSS locators; testing only the happy path; rendering the model's output as HTML.
  • You can now: write an end-to-end test suite for the chat interface of an LLM feature.

12. References

ID Title Publisher URL Accessed Relevance
R1 Installation Playwright (Python) https://playwright.dev/python/docs/intro 2026-10-31 pip install pytest-playwright, playwright install
R2 Pytest Plugin Reference Playwright (Python) https://playwright.dev/python/docs/test-runners 2026-10-31 The page fixture; --headed, --browser, --tracing
R3 Locators Playwright (Python) https://playwright.dev/python/docs/locators 2026-10-31 Prefer get_by_role
R4 Auto-waiting Playwright (Python) https://playwright.dev/python/docs/actionability 2026-10-31 Auto-waiting actions
R5 Assertions Playwright (Python) https://playwright.dev/python/docs/test-assertions 2026-10-31 Auto-retrying assertions
R6 LLM05:2025 Improper Output Handling OWASP GenAI Security Project https://genai.owasp.org/llmrisk/llm052025-improper-output-handling/ 2026-10-31 XSS when the LLM's output is executed by the browser

Key terms (English ↔ Vietnamese)

English Tiếng Việt
End-to-end (E2E) test Test đầu-cuối qua giao diện thật
Locator Cách tìm phần tử trên trang
Web-first assertion Assertion tự chờ và thử lại
Headless / headed Chạy ẩn / hiện trình duyệt
Trace Bản ghi từng bước của một lần chạy
XSS (cross-site scripting) Chèn mã chạy trong trình duyệt người dùng