今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

Locators & Web-First Assertions (Playwright + TypeScript, Ch.3)

kadir 2026年06月08日 20:53 3 次阅读 来源:Dev.to

In Chapter 2 we wrote our first tests and hit two bugs. Before we add more, we need the one skill everything else rests on: finding elements reliably . Get this right and your tests survive redesigns; get it wrong and they break every sprint. Code for this chapter is tagged ch-03 in the repo: https://github.com/aktibaba/playwright-qa-course — see src/tests/ui/locators.spec.ts . Locate the way a user perceives The brittle instinct is to grab elements by their structure — CSS classes, nth-child , XPath. All of that changes the moment a developer touches the markup. Playwright's recommended locators instead target what a user (and a screen reader) perceives: the role, the label, the visible text. Use them in this order of preference: getByRole — the role + accessible name (covers the vast majority of cases) getByLabel — form fields by their <label> getByPlaceholder — inputs without a label getByText — non-interactive content getByTestId — a deliberate data-testid , only when nothing semantic fits Here's the top of the priority list, live against Inkwell's home page: import { test , expect } from " @playwright/test " ; test ( " prefer role-based locators over CSS " , async ({ page }) => { await page . goto ( " / " ); await expect ( page . getByRole ( " button " , { name : " Global Feed " })). toBeVisible (); await expect ( page . getByRole ( " link " , { name : " Sign up " })). toBeVisible (); await expect ( page . getByRole ( " heading " , { name : " inkwell " })). toBeVisible (); }); getByRole("button", { name: "Global Feed" }) asserts two things at once — that an element with the button role exists and that its accessible name is "Global Feed". If a dev swaps the <div class="feed-btn"> for a real <button> , this locator keeps working; a CSS selector wouldn't. Strict mode is your friend Playwright locators are strict : if a locator matches more than one element, the action throws instead of silently picking the first. That catches ambiguous tests before they pick the

本文内容来源于互联网,版权归原作者所有
查看原文