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.
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.
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.
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.
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.
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.
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.
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.
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.
// 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.
- 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.
- "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."