QA AND TEST AUTOMATION · PART 5 · UI WEB AUTOMATION · PLAYWRIGHT · 50 OF 112

Playwright Tutorial: Your First End-to-End Tests

A first end-to-end suite with Playwright Test in TypeScript against ShopRung: installing, the config file with baseURL, test and expect, locators and web-first assertions, resetting data through the request fixture, running headed, filtered and in UI mode, and the HTML report. Three real tests (search, out of stock, log in and add to cart) passed in 1.7 s. Java and Python versions shown too.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 13

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Config and baseURL
  • test + page
  • role and label locators
  • filter and chain
  • expect
  • API reset
  • run modes

Notes

Install

One command creates a project: npm init playwright at latest. It asks a few questions: TypeScript or JavaScript, where tests live, whether to add a GitHub Actions workflow, and whether to download browsers. You get a config file, an example test and the Playwright test package. On a CI machine, playwright install with deps also installs the system libraries the browsers need. TypeScript is the most common choice, and it is what we use here.

Set up
npm init playwright@latest
  TypeScript, tests folder,
  GitHub Actions workflow?
  install browsers? yes

creates:
  playwright.config.ts
  tests/example.spec.ts
  package.json (@playwright/test)
npx playwright install --with-deps

The config

The config holds shared settings. Test dir says where tests are. Base URL comes from an environment variable, defaulting to ShopRung on localhost, so tests can say page go to slash. Trace on first retry records a full trace when a test is retried, which the next episode uses. Retries only on CI. Projects list the browsers and devices to run; here just desktop Chrome, and Part five later adds more.

playwright.config.ts
export default defineConfig({
  testDir: "./tests",
  retries: process.env.CI ? 2 : 0,
  use: {
    baseURL: process.env.BASE_URL
      ?? "http://localhost:8080",
    trace: "on-first-retry",
  },
  projects: [{ name: "chromium",
    use: devices["Desktop Chrome"] }],
});

A first test

A test is the test function with a name and an async body. Playwright gives it fixtures, here page, a fresh browser tab in a fresh, isolated context, like an incognito window. Go to slash, which uses the base URL. Find the search box by its role and its label, search products, and fill in mug. Find the button named search and click. Every action is awaited, because everything in the browser is asynchronous.

tests/shop.spec.ts
import { test, expect } from
  "@playwright/test";

test("search finds the two mugs",
  async ({ page }) => {
  await page.goto("/");
  await page.getByRole("searchbox",
    { name: "Search products" })
    .fill("mug");
  await page.getByRole("button",
    { name: "Search" }).click();

Assertions

Then check the result with web first assertions, which retry until true. The result count should have text two products, and there should be exactly two product cards: the green and the red mug. Other common assertions: to be visible, to be disabled, to have URL, to contain text, to have value, and any of them negated with not. Each assertion is a clear statement of expected behaviour.

... and check
  await expect(page
    .getByTestId("result-count"))
    .toHaveText("2 products");
  await expect(page
    .getByTestId("product-card"))
    .toHaveCount(2);
});

also: toBeVisible, toBeDisabled,
  toHaveURL, toContainText,
  toHaveValue, not.toBeVisible

Scoping

The second test checks the out of stock rule. Go straight to the mug search URL. Take the product cards and filter to the one containing red build mug. Inside that card, its add button, found by a case insensitive pattern on its accessible name, must be disabled, and the card must say out of stock. Filtering and then looking inside, called chaining, is how you write precise locators without long selectors.

Out of stock test
await page.goto("/#/search/mug");
const red = page
  .getByTestId("product-card")
  .filter({ hasText:
    "Red Build Mug" });
await expect(red.getByRole(
  "button", { name:
  /add red build mug/i }))
  .toBeDisabled();
await expect(red)
  .toContainText("Out of stock");

Test data

UI tests need known data. A before each hook runs before every test, and the request fixture is an API client that shares the base URL. Posting to ShopRung's reset endpoint puts the data back to the start, so the red mug is always out of stock and the cart is always empty. A good rule: use the UI for the behaviour you are testing, and the API for setup and cleanup, because it is faster and more reliable.

Hooks and request
test.beforeEach(async
  ({ request }) => {
  await request.post(
    "/api/test/reset");
});

request: an API client that
  shares baseURL
UI for what you test, API for
  setup and cleanup

A user journey

The third test is a small journey. Open the login page, fill email and password by their labels, and click log in. Wait for the user name in the header to be visible, which proves the login finished. Then click add clean code notebook to cart, and expect the cart count to have text one. Real credentials belong in environment variables; ShopRung's practice passwords are public on purpose.

Third test
await page.goto("/#/login");
await page.getByLabel("Email")
  .fill("alice@shoprung.test");
await page.getByLabel("Password")
  .fill("Alice123!");
await page.getByRole("button",
  { name: "Log in" }).click();
await expect(page.getByTestId(
  "user-name")).toBeVisible();
// add notebook, then
// cart-count toHaveText("1")

Running

Run the suite with npx playwright test. Our run: three tests, one worker, three passed in one point seven seconds. By default the browser is headless, with no window. Add headed to watch it, dash g to run tests whose name matches, ui for UI mode, an interactive runner that re runs on save and shows each step, and debug to step through. Show report opens the HTML report, with every test, its steps and any failure.

Commands
npx playwright test
  Running 3 tests using 1 worker
  3 passed (1.7s)

npx playwright test --headed
npx playwright test -g "mugs"
npx playwright test --ui
npx playwright test --debug
npx playwright show-report

Java and Python

Playwright also has official Java, Python and dot net bindings with the same concepts. In Java, page navigate, get by role with an aria role and options, and assert that, with JUnit or TestNG as the runner. In Python, the pytest playwright plugin gives a page fixture, snake case methods like get by role, and expect. The TypeScript runner has the most features, which is why many teams use it even when the app is written in Java.

Other bindings
// Java (com.microsoft.playwright)
page.navigate(BASE);
page.getByRole(AriaRole.BUTTON,
  new Page.GetByRoleOptions()
   .setName("Search")).click();
assertThat(page.getByTestId(
  "result-count")).hasText("2 ...");
# Python (pytest-playwright)
page.get_by_role("button",
  name="Search").click()
expect(page.get_by_test_id(...))

Common mistakes

First suite mistakes. Forgetting await, which makes steps run out of order; the TypeScript linter can catch it. Full URLs in every go to call instead of the base URL. Logging in through the UI in every test, which the fixtures episode fixes. Tests that depend on each other's data. Wait for timeout everywhere. If statements and console logs instead of assertions. And only ever running headed on your laptop, never headless like CI.

Avoid these
  • forgetting await
  • full URLs in every goto
  • logging in through the UI in every test
  • tests sharing state
  • waitForTimeout() everywhere
  • asserting with if/else and console.log
  • only running headed locally

Say it like this

In the interview: the config sets the base URL from the environment, the browsers, retries and tracing. Each test gets a fresh, isolated page. I reset or create data through the request fixture, use role and label locators, chain with filter to scope inside components, and assert with retrying expect calls. Tests run headless in CI in parallel, and I debug from the HTML report and traces.

In the interview
  • "A config sets baseURL from env, browsers and traces.
  • Each test gets an isolated
  • page; I reset data via the request fixture, use role and label locators, chain with filter for scope, and assert
  • with retrying expect. I run
  • headless in CI and read the HTML report and traces."

Interview questions

Q1What is Playwright?

An open-source browser automation framework from Microsoft that drives Chromium, Firefox and WebKit, with auto-waiting, its own test runner, tracing and bindings for TypeScript/JavaScript, Java, Python and .NET.

Q2What is the page fixture?

A new browser page in a fresh, isolated browser context created for each test, so cookies and storage do not leak between tests.

Q3What does baseURL do?

Lets page.goto("/path") and request calls use relative URLs, so the same suite runs against any environment by changing one setting.

Q4What are Playwright projects?

Named configurations in playwright.config, typically one per browser or device, that run the same tests with different settings.

Q5How do you run one Playwright test?

npx playwright test path/to/file.spec.ts, add -g "name" to match test titles, or use test.only while debugging (never commit it).

Q6What is UI mode?

npx playwright test --ui: an interactive runner with a watch mode, a timeline of steps, DOM snapshots and filtering.

Q7What is the request fixture used for?

Making API calls that share baseURL, for setup and cleanup (or API tests) inside UI test files.

Q8Why use filter() on a locator?

To narrow a list of elements, for example product cards, to the one containing certain text or another locator, then chain further locators inside it.