QA and Test Automation · Lab 13 of 35
Playwright End-to-End Tests in TypeScript: ShopRung Lab
Build a Playwright suite in TypeScript from an empty folder: config, role locators, page objects, custom fixtures, logging in once with storageState, and real journeys from search to placed order. Then catch ShopRung bugs and debug them with the HTML report and traces.
⏱ 75 minIntermediate💸 Free8 steps
Node.js 22Playwright Test 1.63TypeScriptChromiumShopRung
Overview video
What you will build
A Playwright Test project in TypeScript that drives ShopRung in a real browser, with a login setup and 6 tests across three journeys:
- Search: the mug search, case-insensitive search, and the out of stock mug whose button is disabled.
- Cart: four notebooks, exactly $50.00, with SAVE10 for a total of $49.99; free shipping on a $75.00 keyboard.
- Checkout: place an order and see Thank you! Your order is placed., status PLACED, total $29.98 and an empty cart.
Built the way teams build it: ProductsPage and CartPage page objects, custom fixtures with an automatic data reset, and one login saved as storageState instead of a login in every test.
Before you start
- Basic JavaScript or TypeScript:
const, functions,asyncandawait. TypeScript for Playwright covers what you need. - The episodes this lab puts into practice: Playwright basics, DOM and locators, Page Object Model and Fixtures and login state.
- ShopRung installed, as in lab 1 setup. You already have Node.js 22 from that setup.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start in its folder, and leave that terminal open. Open http://localhost:8080 in your browser once to see the shop.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"status":"UP","app":"ShopRung","version":"1.0.0"} S2Check Node.js
Playwright needs Node.js 18 or newer; ShopRung already needs 22.13, so you are set.
node --version v22.13.0 (or newer)
S3A code editor
VS Code with the official Playwright Test for VS Code extension is the easiest: it runs single tests from the editor and has a locator picker. Any editor works; every step also works in a terminal.
Create the project and install Playwright
A folder with Playwright Test installed at a pinned version, and the Chromium browser downloaded.
Open a new terminal (ShopRung keeps the other one) and make a project folder. npm init playwright@latest can generate everything, but writing the files yourself once means you know what each one does.
Create package.json with the content below. It pins @playwright/test to one exact version, so your teammates and CI get the same runner. The scripts give you npm test and npm run report. Add the .gitignore too: saved logins, results and reports never go into Git.
Then install. npx playwright install chromium downloads the browser build this Playwright version is tested with (about 150 MB, once).
{
"name": "shoprung-e2e",
"private": true,
"scripts": {
"test": "playwright test",
"report": "playwright show-report"
},
"devDependencies": {
"@playwright/test": "1.63.0"
}
} - An exact version, no
^. Upgrading the test runner should be a deliberate change in a pull request.line 9
node_modules/
playwright/.auth/
test-results/
playwright-report/ - Saved logins hold real tokens. Never commit them.line 2
mkdir shoprung-e2e
cd shoprung-e2e
# create package.json and .gitignore here, then:
npm install
npx playwright install chromium added 3 packages ... Downloading Chromium ... 100%
Stuck on this step?
- Linux: the browser starts but complains about missing libraries.
- Run
npx playwright install --with-deps chromium, which also installs the system libraries (it asks for your password).
The config file
playwright.config.ts with the base URL, one browser, reports and failure evidence.
Create playwright.config.ts. Every test reads its settings from here:
baseURLcomes from theBASE_URLenvironment variable, with ShopRung on localhost as the default, so tests writepage.goto('/').workers: 1andfullyParallel: false: every test resets the one shared ShopRung, so tests must not run at the same time. The parallel episode shows what happens otherwise.trace: 'on-first-retry'andscreenshot: 'only-on-failure'record evidence only when something goes wrong.- One project: desktop Chrome.
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: false, // the tests share one ShopRung and reset it, so run one at a time
workers: 1,
retries: process.env.CI ? 2 : 0,
reporter: [['list'], ['html', { open: 'never' }]],
use: {
baseURL: process.env.BASE_URL ?? 'http://localhost:8080',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
],
}); - One shared shop, one test at a time. Isolated data per test is what lets you raise this later.line 6
- Retries only on CI (the
CIvariable is set there). Locally a failure should fail.line 7 - Run against another server with
BASE_URL=http://... npx playwright test.line 10 - A full trace when a test is retried: actions, DOM snapshots, network.line 11
Your first test: search
One passing test that searches like a user and checks the result.
Create tests/search.spec.ts. The beforeEach hook uses the request fixture, an API client that shares the base URL, to reset ShopRung before each test.
The test finds the search box by its role and label, the way a user and a screen reader find it, fills in mug, clicks the button named Search, and checks the result with web-first assertions, which retry until the page shows the expected text. No sleeps anywhere.
import { test, expect } from '@playwright/test';
test.beforeEach(async ({ request }) => {
await request.post('/api/test/reset');
});
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();
await expect(page.getByTestId('result-count')).toHaveText('2 products');
await expect(page.getByTestId('product-card').filter({ hasText: 'Green Build Mug' })).toBeVisible();
}); - Set up data through the API: fast and reliable. The UI is for what you test.line 4
- Role + accessible name: the most stable kind of locator.line 9
- Retries for up to 5 seconds until the count is right.line 11
- Narrow the 2 cards to the one that contains this text.line 12
npx playwright test Running 1 test using 1 worker ✓ 1 [chromium] › tests/search.spec.ts:7:5 › search finds the two mugs (612ms) 1 passed (1.1s)
Stuck on this step?
Error: connect ECONNREFUSED 127.0.0.1:8080- ShopRung is not running. Start it with
npm startin its own terminal.
Page objects and fixtures
ProductsPage and CartPage own the locators; a fixture file resets the shop and hands tests ready page objects.
As the suite grows, the same locators would appear in every test. Move them into page objects (pages/ProductsPage.ts and pages/CartPage.ts): each holds its locators once and offers user actions like searchFor and applyCoupon.
Then create tests/fixtures.ts. It extends Playwright's test with your own fixtures: resetShop runs automatically before every test, products opens the product list and gives the test a ready ProductsPage, and cart gives a CartPage. Tests import test and expect from this file instead of from Playwright.
Finally replace tests/search.spec.ts: the reset hook is gone (the fixture does it), and the tests read like the behaviour. Two tests are new: upper-case search, and the out of stock mug.
import type { Locator, Page } from '@playwright/test';
/** The product list: search, the result count and one card per product. */
export class ProductsPage {
readonly search: Locator;
readonly count: Locator;
readonly cartCount: Locator;
constructor(private readonly page: Page) {
this.search = page.getByRole('searchbox', { name: 'Search products' });
this.count = page.getByTestId('result-count');
this.cartCount = page.getByTestId('cart-count');
}
async open() {
await this.page.goto('/');
}
async searchFor(term: string) {
await this.search.fill(term);
await this.search.press('Enter');
}
card(name: string) {
return this.page.getByTestId('product-card').filter({ hasText: name });
}
async addToCart(name: string) {
await this.card(name).getByRole('button', { name: `Add ${name} to cart` }).click();
}
} - Locators are lazy: defining them does not touch the page until they are used.line 5
- Enter submits the search form, like a user would.line 21
- A parameterised locator: one product card by its name.line 24
- The button's accessible name is "Add <product> to cart", not its visible text.line 29
import type { Locator, Page } from '@playwright/test';
/** The cart: lines, the coupon form, the totals and the Place order button. */
export class CartPage {
readonly lines: Locator;
readonly couponMessage: Locator;
readonly subtotal: Locator;
readonly discount: Locator;
readonly shipping: Locator;
readonly total: Locator;
constructor(private readonly page: Page) {
this.lines = page.getByTestId('cart-line');
this.couponMessage = page.getByTestId('coupon-message');
this.subtotal = page.getByTestId('subtotal');
this.discount = page.getByTestId('discount');
this.shipping = page.getByTestId('shipping');
this.total = page.getByTestId('total');
}
async open() {
await this.page.goto('/#/cart');
}
async setQuantity(name: string, quantity: number) {
const input = this.page.getByLabel(`Quantity of ${name}`);
await input.fill(String(quantity));
await input.press('Tab'); // the cart saves the new quantity when the field loses focus
}
async applyCoupon(code: string) {
await this.page.getByLabel('Coupon code').fill(code);
await this.page.getByRole('button', { name: 'Apply' }).click();
}
async placeOrder() {
await this.page.getByTestId('checkout').click();
}
} - Each quantity field has a hidden label naming its product.line 26
- The cart saves a new quantity on change, which fires when the field loses focus.line 28
- A test id where there is no better handle. The visible text is "Place order".line 37
import { test as base } from '@playwright/test';
import { CartPage } from '../pages/CartPage';
import { ProductsPage } from '../pages/ProductsPage';
type Fixtures = { resetShop: void; products: ProductsPage; cart: CartPage };
export const test = base.extend<Fixtures>({
// Runs before every test: ShopRung back to its seed data.
resetShop: [async ({ request }, use) => {
await request.post('/api/test/reset');
await use();
}, { auto: true }],
products: async ({ page }, use) => {
const products = new ProductsPage(page);
await products.open();
await use(products);
},
cart: async ({ page }, use) => {
await use(new CartPage(page));
},
});
export { expect } from '@playwright/test'; { auto: true }runs it for every test, asked for or not.line 9useruns the test. Anything after it would be clean-up.line 11- Asking for
productsgives an opened product list.line 13
import { test, expect } from './fixtures';
test('search finds the two mugs', async ({ products }) => {
await products.searchFor('mug');
await expect(products.count).toHaveText('2 products');
await expect(products.card('Green Build Mug')).toBeVisible();
});
test('search is not case sensitive', async ({ products }) => {
await products.searchFor('MUG');
await expect(products.count).toHaveText('2 products');
});
test('the out of stock mug cannot be added', async ({ products }) => {
await products.searchFor('mug');
const red = products.card('Red Build Mug');
await expect(red).toContainText('Out of stock');
await expect(red.getByRole('button', { name: 'Add Red Build Mug to cart' })).toBeDisabled();
}); - Your extended test, with the custom fixtures.line 1
- CART rule: an out of stock product cannot be added.line 18
npx playwright test ✓ 1 [chromium] › tests/search.spec.ts:3:5 › search finds the two mugs ✓ 2 [chromium] › tests/search.spec.ts:9:5 › search is not case sensitive ✓ 3 [chromium] › tests/search.spec.ts:14:5 › the out of stock mug cannot be added 3 passed (2.4s)
Log in once with storageState
A setup project logs Alice in through the real login page once; every other test starts logged in.
Cart and checkout need a logged-in user. Logging in through the form in every test is slow and repeats the same steps. Instead, create tests/auth.setup.ts: it logs in once, waits until the header says Hi, Alice Shah, and saves the browser's storage (cookies and localStorage, where ShopRung keeps its token) to playwright/.auth/alice.json.
Then replace playwright.config.ts. A new setup project runs files ending in .setup.ts; the chromium project depends on it and loads the saved state, so every test opens ShopRung already logged in as Alice. Data resets do not log Alice out: her account stays the same.
import { test as setup, expect } from '@playwright/test';
// Logs Alice in once through the real login page and saves the browser state for every other test.
setup('log in as alice', async ({ page }) => {
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')).toHaveText('Hi, Alice Shah');
await page.context().storageState({ path: 'playwright/.auth/alice.json' });
}); - Labels, not CSS: the form's inputs are wrapped in their labels.line 6
- Wait until login has really finished, or you save a logged-out state.line 9
- Saves cookies and localStorage for the site to a JSON file.line 10
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: false, // the tests share one ShopRung and reset it, so run one at a time
workers: 1,
retries: process.env.CI ? 2 : 0,
reporter: [['list'], ['html', { open: 'never' }]],
use: {
baseURL: process.env.BASE_URL ?? 'http://localhost:8080',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/alice.json' },
dependencies: ['setup'],
},
],
}); - Runs first, because chromium depends on it.line 15
- Every test's browser starts with Alice's saved login.line 18
npx playwright test ✓ 1 [setup] › tests/auth.setup.ts:4:6 › log in as alice ✓ 2 [chromium] › tests/search.spec.ts:3:5 › search finds the two mugs ... 4 passed (3.1s)
The cart journey: SAVE10 on its boundary
Two cart tests: SAVE10 at exactly $50.00, and free shipping at exactly $75.00.
Create tests/cart.spec.ts. The first test is the rule from lab 1, now in a browser: add one Clean Code Notebook, wait for the cart badge to say 1, open the cart, set the quantity to 4 (exactly $50.00), apply save10 in lower case, and check every number the shopper sees: Coupon applied, -$5.00, $4.99 shipping and $49.99 total.
Waiting for the badge before opening the cart matters: adding is a request to the server, and the cart page loads the cart from the server. Assert the state, then move on.
import { test, expect } from './fixtures';
test('SAVE10 at exactly $50.00 gives a total of $49.99', async ({ products, cart }) => {
await products.addToCart('Clean Code Notebook');
await expect(products.cartCount).toHaveText('1');
await cart.open();
await cart.setQuantity('Clean Code Notebook', 4);
await expect(cart.subtotal).toHaveText('$50.00');
await cart.applyCoupon('save10');
await expect(cart.couponMessage).toHaveText('Coupon applied');
await expect(cart.discount).toHaveText('-$5.00');
await expect(cart.shipping).toHaveText('$4.99');
await expect(cart.total).toHaveText('$49.99');
});
test('shipping is free from $75.00', async ({ products, cart }) => {
await products.addToCart('Quiet Mechanical Keyboard');
await expect(products.cartCount).toHaveText('1');
await cart.open();
await expect(cart.shipping).toHaveText('Free');
await expect(cart.total).toHaveText('$75.00');
}); - Synchronise on the result of the add before leaving the page.line 5
- 4 × $12.50 = $50.00: exactly the SAVE10 minimum.line 7
- Lower case on purpose: codes are not case sensitive.line 9
- At $75.00 after the discount, shipping shows "Free".line 20
npx playwright test tests/cart.spec.ts ✓ 1 [setup] › tests/auth.setup.ts:4:6 › log in as alice ✓ 2 [chromium] › tests/cart.spec.ts:3:5 › SAVE10 at exactly $50.00 gives a total of $49.99 ✓ 3 [chromium] › tests/cart.spec.ts:16:5 › shipping is free from $75.00 3 passed (2.6s)
Checkout: place an order
One end-to-end journey from product to placed order, checking the confirmation, status, total and the empty cart.
Create tests/checkout.spec.ts. Add the Testing Field Guide ($24.99), open the cart and click Place order. The shop shows the order page with Thank you! Your order is placed., status PLACED, total $29.98 ($24.99 plus $4.99 shipping), and the cart badge goes back to 0.
Keep journeys like this few and valuable: one per critical path. The detailed rules (every coupon, every boundary) are faster and more stable at the API level, as in the pytest API lab.
import { test, expect } from './fixtures';
test('placing an order shows it as PLACED and empties the cart', async ({ page, products, cart }) => {
await products.addToCart('Testing Field Guide');
await expect(products.cartCount).toHaveText('1');
await cart.open();
await cart.placeOrder();
await expect(page.getByTestId('order-placed')).toHaveText('Thank you! Your order is placed.');
await expect(page.getByTestId('order-status')).toHaveText('PLACED');
await expect(page.getByTestId('order-total')).toHaveText('$29.98');
await expect(products.cartCount).toHaveText('0');
}); - The confirmation only shows right after placing.line 8
- $24.99 + $4.99 shipping: under $75.00, so shipping is charged.line 10
- A side effect the user sees: the cart is empty again.line 11
npx playwright test Running 7 tests using 1 worker ✓ 1 [setup] › tests/auth.setup.ts:4:6 › log in as alice (687ms) ✓ 2 [chromium] › tests/cart.spec.ts:3:5 › SAVE10 at exactly $50.00 gives a total of $49.99 (734ms) ✓ 3 [chromium] › tests/cart.spec.ts:16:5 › shipping is free from $75.00 (487ms) ✓ 4 [chromium] › tests/checkout.spec.ts:3:5 › placing an order shows it as PLACED and empties the cart (539ms) ✓ 5 [chromium] › tests/search.spec.ts:3:5 › search finds the two mugs (392ms) ✓ 6 [chromium] › tests/search.spec.ts:9:5 › search is not case sensitive (365ms) ✓ 7 [chromium] › tests/search.spec.ts:14:5 › the out of stock mug cannot be added (341ms) 7 passed (5.4s)
Watch, debug and read the report
Run the suite in UI mode and headed, and open the HTML report.
--ui opens UI mode: a window listing every test, a timeline of each step with DOM snapshots, and a watch mode that reruns a test when you save. --headed shows the real browser while tests run. npm run report opens the HTML report from the last run: every test, every step, and for failures the screenshot and trace.
Try the locator picker in UI mode: hover any element in ShopRung and it shows the locator Playwright would use. Compare it with the ones in your page objects.
npx playwright test --ui
npx playwright test --headed
npm run report UI mode opens a window; --headed shows Chrome; the report opens at http://localhost:9323
Check it works
Switch on ShopRung's coupon-boundary bug and run the suite. Exactly one test fails, and the error tells you why: the coupon message never appeared, because the shop refused SAVE10 at $50.00. Open the report (npm run report) and look at the screenshot: the shop shows its own error message instead.
Then try free-shipping-boundary (the free shipping test fails) and search-case (both search tests fail). Now try slow-search: search takes 2.5 seconds, and all 7 still pass, because web-first assertions wait for the page. That is the difference between a stable suite and a flaky one. Turn the bugs off at the end with -d '{"enabled":[]}'.
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["coupon-boundary"]}'
npx playwright test 1) [chromium] › tests/cart.spec.ts:3:5 › SAVE10 at exactly $50.00 gives a total of $49.99
Error: expect(locator).toHaveText(expected) failed
Locator: getByTestId('coupon-message')
Expected: "Coupon applied"
Timeout: 5000ms
Error: element(s) not found
1 failed
6 passed (10.3s) Troubleshooting
browserType.launch: Executable doesn't exist
The browser was not downloaded for this Playwright version. Run npx playwright install chromium again in the project folder.
Cart tests fail with an empty cart, or as if logged out.
The setup project did not run or saved too early. Run the whole suite (not just one file with --no-deps), and check playwright/.auth/alice.json contains shoprung.token.
strict mode violation: ... resolved to 12 elements
A locator matched several elements, for example getByRole('button', { name: 'Add to cart' }). Scope it inside one card, or use the full accessible name.
Tests pass alone but fail together.
Something leaks between tests. Check workers: 1 is still set, and that every test imports test from ./fixtures, so the reset runs.
Windows: the curl -d command for the bug switch fails.
Use curl.exe and -d "{\"enabled\":[\"coupon-boundary\"]}", or open the shop and use the bug switch link in the footer.
What changes in production
- Teams keep UI journeys few (the critical paths) and push rule-by-rule checks down to API and unit tests, where they run in milliseconds.
- Real suites create data per test (often a new user through the API) instead of resetting a shared environment, which is what allows
fullyParalleland many workers. - CI runs the suite headless on every pull request, uploads the HTML report and traces as artifacts, and shards large suites across machines.
- Credentials for the setup login come from CI secrets, and one setup file per role (customer, admin) keeps role tests simple.
Interview angle
“Walk me through how you would structure a Playwright test suite.”
A config with the base URL from the environment, browser projects, and traces and screenshots on failure. A setup project logs in once per role and saves storageState; test projects depend on it. Locators live in page objects and use roles, labels and test ids. Custom fixtures handle data and hand tests ready page objects, so tests read like behaviour. Assertions are web-first, so there are no sleeps. A few UI journeys cover the critical paths, detailed rules are tested at the API level, and CI keeps the report and traces for every failure.
Clean up
The full project
Every file from this lab, as it is after the last step.