← Practical QA

💻 Practical QA — Code Library

Every code example from the course's automation content — 47 annotated examples. Copy, paste, and practise against the FreshNest lab project. 29 examples are complete, syntax-verified code; the rest are teaching excerpts (patterns and configuration tables) and are presented as such in their lessons.

⬇ Download the runnable FreshNest lab project (Playwright + TypeScript, with the buggy & fixed practice sites)

B-01 — What automation is (and is not)

Example 1

test("[TC-001] HomePage loads with correct title and heading", async ({ page }) => {
  const po = new HomePage(page);
  await po.goto();
  await po.expectLoaded();
});

From the module's full text.

B-02 — How a web page works

Example 1

page.locator("h1").first()

Read it as English: “on the page, find the first top-level heading.” This is how the aomaai.com suite's HomePage finds its main heading — no magic, just the DOM being questioned.

Example 2

this.mainHeading = page.locator("h1").first();

From the module's full text.

Example 3

await expect(this.page).toHaveTitle("Aoma AI Agency — Get Found. Miss Fewer Leads.");

From the module's full text.

B-03 — Your first automated test, line by line

Example 1

test("[TC-001] HomePage loads with its expected title and heading", async ({ page }) => {

test(...) declares a test. The title carries the ID. And { page } is the browser page the framework hands you — your window into the DOM from B-02.

Example 2

const po = new HomePage(page);
await po.goto();
await po.expectLoaded();

1) Build the page object. 2) Go to the page. 3) Verify it loaded correctly. That's the entire test — three honest lines.

Example 3

test("[TC-001] HomePage loads with correct title and heading", async ({ page }) => {
  const po = new HomePage(page);
  await po.goto();
  await po.expectLoaded();
});

From the module's full text.

Example 4

test("[TC-001] HomePage loads with correct title and heading", async ({ page }) => {

From the module's full text.

Example 5

const po = new HomePage(page);

From the module's full text.

Example 6

await po.goto();

From the module's full text.

Example 7

await po.expectLoaded();

From the module's full text.

B-04 — Locators

Example 1

page.getByRole("button", { name: "Send" })
page.locator('a[href="/privacy.html"]')

By role + name: “the Send button.” By stable attribute: “the link pointing at /privacy.html.” Both describe what the element IS, not where it happens to sit.

Example 2

// 1. By element type
this.mainHeading = page.locator("h1").first();

// 2. By attribute (href)
linkByHref(href: string) {
  return this.page.locator(`a[href="${href}"]`).first();
}

// 3. By role + visible label — the most human way
buttonByText(text: string) {
  return this.page.getByRole("button", { name: text }).first();
}

// 4. By a precise selector for a form field
field(selector: string) {
  return this.page.locator(selector).first();
}

From the module's full text.

Example 3

constructor(page: Page) {
  this.page = page;
  this.mainHeading = page.locator("h1").first();
}

From the module's full text.

B-05 — Page objects

Example 1

export class HomePage {
  readonly expectedTitle = "Aoma AI Agency — …";
  constructor(page) { this.page = page; }
  async goto() { await this.page.goto("/"); }
  async expectLoaded() { /* asserts title + heading */ }
}

Facts at the top (expectedTitle). The constructor takes the browser page. Then verbs: goto, expectLoaded. Facts and verbs — that's the whole anatomy (OOP track, O-02/O-03).

Example 2

export class HomePage {
  readonly page: Page;
  readonly path = "/";
  readonly expectedTitle = "Aoma AI Agency — Get Found. Miss Fewer Leads.";
  readonly mainHeading: Locator;

  constructor(page: Page) {
    this.page = page;
    this.mainHeading = page.locator("h1").first();
  }

  async goto() {
    await this.page.goto(this.path);
  }

  async expectLoaded() {
    await expect(this.page).toHaveTitle(this.expectedTitle);
    await expect(this.mainHeading).toContainText("Get found on Google & AI search. Miss fewer leads.");
  }
}

From the module's full text.

B-07 — Smoke & regression suites

Example 1

page.on("pageerror", e => errors.push(String(e)));
// …visit the page, wait a beat…
expect(errors).toEqual([]);

“Visit the page and confirm nothing exploded” — TC-004 in your suite. Breadth over depth is the smoke philosophy: every page loads, links respond, forms are present, no JS errors.

Example 2

test("[TC-004] HomePage loads without uncaught JS errors", async ({ page }) => {
  const errors: string[] = [];
  page.on("pageerror", (e) => errors.push(String(e).slice(0, 160)));
  const po = new HomePage(page);
  await po.goto();
  await page.waitForTimeout(1200);
  expect(errors, "uncaught JS errors on load: " + errors.join(" | ")).toEqual([]);
});

From the module's full text.

B-08 — End-to-end journeys

Example 1

const btn = page.getByText(label).first();
await btn.click();
expect(new URL(page.url()).pathname).toBe("/");

TC-009 does a story fragment: click a control, then prove the user is still where the story says. Full journeys are these pieces composed — Page Objects snapping together like train cars.

Example 2

for (const label of ["Show my score →", "Copy my score summary"]) {
  const btn = page.getByText(label, { exact: false }).first();
  if (await btn.isVisible().catch(() => false)) {
    await btn.click({ timeout: 3000 }).catch(() => {});
    await page.waitForTimeout(400);
    const pn = new URL(page.url()).pathname;
    const here = (pn.endsWith("/") && pn.length > 1 ? pn.slice(0, -1) : pn) || "/";
    expect(here, "control " + label + " should not navigate away").toBe("/");
  }
}

From the module's full text.

B-09 — Forms & workflows

Example 1

const fld = po.field("#g-name");
if ((await fld.count()) && (await fld.isVisible())) {
  await fld.fill("QA Tester");
  await expect(fld).toHaveValue("QA Tester");
}

Find the field → only proceed if it's actually there and visible → fill with obviously-fake data → assert the value stuck. That pattern repeats per field: name, business, email (qa@example.com), phone (5551234567).

Example 2

test("[TC-007] HomePage form fields accept input (fill only, never submits on a live site)", async ({ page }) => {
  const po = new HomePage(page);
  await po.goto();
  const fld0 = po.field("#g-name");
  if ((await fld0.count()) && (await fld0.isVisible().catch(() => false))) {
    await fld0.scrollIntoViewIfNeeded().catch(() => {});
    await fld0.fill("QA Tester", { timeout: 4000 }).catch(() => {});
    await expect(fld0).toHaveValue("QA Tester");
  }
  // …the same pattern repeats for #g-biz, #g-email (filled with qa@example.com),
  // #g-phone (filled with 5551234567) and the chat input #cin.
});

From the module's full text.

B-10 — Data-driven testing

Example 1

const hrefs = ["/", "/privacy.html", "/terms.html"];
for (const href of hrefs) {
  expect(domPaths).toContain(href);
  // …request the target, expect status < 400…
}

Data-driven at its smallest scale, inside TC-002: the list is data, the loop body is the template. New page on the site → add one string → coverage grows.

Example 2

test("[TC-S001] Welcome heading is visible", async ({ page }) => {
  await page.goto("/");
  await expect(page.getByText("Welcome heading is visible").first()).toBeVisible();
});

Give TestGen a sheet (ID, Page, Check — from Excel, Sheets, Jira, Trello) and it generates one test per row, titled with YOUR ID. TC-S001 came from the sheet — not from TestGen.

Example 3

const hrefs = ["/", "/privacy.html", "/terms.html"];
// …read the links actually rendered on the page…
for (const href of hrefs) {
  expect(domPaths, `a link to ${href} should be rendered on the page`).toContain(href);
  // …request the target and expect its status to be < 400…
}

From the module's full text.

Example 4

/** Generated from your sheet: example-sheet.csv — one test per row, titled with YOUR case ID. */

test("[TC-S001] Welcome heading is visible", async ({ page }) => {
  await page.goto("/");
  await expect(page.getByText("Welcome heading is visible").first()).toBeVisible();
});

test("[TC-S002] Privacy Policy heading is visible", async ({ page }) => {
  await page.goto("/privacy.html");
  await expect(page.getByText("Privacy Policy heading is visible").first()).toBeVisible();
});

From the module's full text.

B-11 — API testing basics

Example 1

const r = await fetch(target, { method: "HEAD" });
if (r.status !== 405) status = r.status;
expect(status).toBeGreaterThan(0);
expect(status).toBeLessThan(400);

Inside TC-002: ask cheaply first (HEAD = “just your status, not the whole page”), fall back if refused, then assert a RANGE — anything under 400 is healthy, because redirects are fine too. Request → status → assertion: an API test in miniature.

Example 2

const target = new URL(href, page.url()).toString();
let status = 0;
try { const r = await fetch(target, { method: "HEAD", redirect: "follow" }); if (r.status !== 405) status = r.status; } catch {}
if (!status) { try { const r = await fetch(target, { redirect: "follow" }); status = r.status; } catch {} }
if (!status) { const res = await request.get(href).catch(() => null); status = res ? res.status() : 0; }
expect(status, `target ${href} should respond < 400`).toBeGreaterThan(0);
expect(status, `target ${href} should respond < 400`).toBeLessThan(400);

From the module's full text.

B-12 — Visual testing

Example 1

use: { baseURL, trace: "on", video: "on", screenshot: "only-on-failure" }

From the module's full text.

B-13 — Accessibility testing

Example 1

page.getByRole("button", { name: "Send" })

Role + name is exactly what a screen reader announces (“button, Send”). When your test finds elements the way assistive tech experiences them, passing tests quietly PROVE those names exist. If getByRole can't find it — a screen reader probably can't either.

B-14 — Responsive & cross-browser projects

Example 1

"iPhone 15": viewport 393×852, scale 3, touch,
userAgent “…iPhone; CPU iPhone OS 17_5… Safari/604.1"

A device preset is a bundle of honest facts: size, pixel density, touch, and the user-agent the site uses to decide what to serve. (Quirk in plain sight: Firefox doesn't support isMobile — the runner deletes the flag for Firefox projects.)

Example 2

"Desktop":    viewport 1280 × 800
"iPhone 15":  viewport 393 × 852, deviceScaleFactor 3, isMobile, hasTouch,
              userAgent "…iPhone; CPU iPhone OS 17_5… Safari/604.1"
"Pixel 7":    viewport 412 × 915, Android 14, Chrome mobile
"iPad":       viewport 820 × 1180, hasTouch

From the module's full text.

Example 3

projects: [ { name: "firefox · Desktop", use: { browserName: "firefox", … } },
            { name: "firefox · iPhone 15", use: { … } }, … ]

From the module's full text.

B-15 — Unit testing

Example 1

test("free shipping at exactly $75", () => {
  expect(shippingFor(75)).toBe(0);
});
test("standard shipping below $75", () => {
  expect(shippingFor(74.99)).toBe(6.95);
});

Written for this tutorial (labeled, as always): notice what's ABSENT — no page, no goto, no waiting. Just input → expected output. And notice the cases: AT the line ($75) and one cent below — rules break at their boundaries.

Example 2

import { test, expect } from "@playwright/test";
import { shippingFor } from "../src/pricing";

// The rule under test: orders of $75+ ship free; below that, $6.95.
test("free shipping at exactly $75", async () => {
  expect(shippingFor(75)).toBe(0);
});

test("standard shipping below $75", async () => {
  expect(shippingFor(74.99)).toBe(6.95);
});

From the module's full text.

O-01 — OOP · classes & objects

Example 1

class HomePage { /* the blueprint */ }

const po = new HomePage(page);

HomePage is the class. The word new builds one object from it. po is that object — the house you can actually walk into.

O-02 — OOP · properties & the constructor

Example 1

readonly expectedTitle = "Aoma AI Agency — Get Found. Miss Fewer Leads.";

constructor(page: Page) {
  this.page = page;
}

expectedTitle is a fact HomePage carries. The CONSTRUCTOR is a special method that runs the moment an object is built with new — here it receives the browser page and stores it: this.page means “the page stored on THIS object.”

O-03 — OOP · methods

Example 1

async goto() {
  await this.page.goto(this.path);
}

A method can use the object's own properties — this.page and this.path, the facts from O-02. Verbs act on the object's nouns. That's most of OOP, honestly.

A-01 — POM architecture

Example 1

timeout: 60_000,
expect: { timeout: 8_000 },
fullyParallel: true, retries: 1,
reporter: [["html", …], ["json", { outputFile: "test-results/results.json" }]]

From your real config: two timeouts on purpose (60s whole test, 8s per expect). fullyParallel + 1 retry is a CONTRACT — tests must be independent, or parallelism exposes it. And results.json isn't a log; it's a data contract the Excel and tracker tools consume.

Example 2

export default defineConfig({
  testDir: "./tests",
  timeout: 60_000,
  expect: { timeout: 8_000 },
  fullyParallel: true,
  retries: 1,
  reporter: [
    ["list"],
    ["html", { open: "never", outputFolder: "playwright-report" }],
    ["json", { outputFile: "test-results/results.json" }]
  ],
  use: {
    baseURL: "https://aomaai.com",
    trace: "retain-on-failure",
    screenshot: "only-on-failure",
    // …
  },
  projects: [ /* Desktop Chrome / Firefox / Safari, iPhone 15, Pixel 7 */ ]
});

From the module's full text.

Example 3

export class HomePage {
  readonly header: SiteHeader;           // component, built once, reused everywhere
  constructor(page: Page) {
    this.page = page;
    this.header = new SiteHeader(page);  // the page composes its regions
    this.mainHeading = page.locator("h1").first();
  }
}

From the module's full text.

A-02 — Regression engineering — tagging

Example 1

test("[TC-214] @checkout @forms Guest checkout totals include tax", …)

The full professional name carries both worlds: the TC-ID keeps traceability to the sheet/Jira case; the tags make it selectable by area and layer. “Everything covering checkout + last month's results” = tags × IDs × history.

A-03 — Fixtures, state & cleanup

Example 1

// Pattern (illustrative, built on the real Page Objects from B-05):
// a "loggedInPage" fixture logs in ONCE, as a TEST account, before the
// test body runs — the test starts already inside the story.
test("checkout journey", async ({ loggedInPage }) => {
  const home = new HomePage(loggedInPage);
  // …the story begins here, state already true…
});

From the module's full text.

A-06 — API testing in the suite

Example 1

API: create a fresh listing (marked with this run's ID)
UI:  open its page → assert it renders with the API's values
API: fetch it → assert view-state recorded
API: delete it (cleanup)

The HYBRID pattern: each surface does what it's most truthful at. UI stays short because the API did the commuting. Most “slow UI suite” rescues are this pattern, applied with discipline.

Example 2

API: create a fresh listing (test data, marked with this run's ID)
UI:  open the listing page → assert it renders with the API's values
API: fetch the listing → assert view-state recorded correctly
API: delete the listing (cleanup, A-03)

From the module's full text.

A-12 — Integrations

Example 1

const jira = title.match(/\b([A-Z][A-Z0-9]+-\d+)\b/);
const trello = title.match(/trello:([a-zA-Z0-9]+)/);
// post: `Automated regression — <time>: PASS — "<title>"` as a COMMENT

From your suite's real tools/push-results.mjs: a test is linked when its TITLE carries the tracker key — [PROJ-123] for Jira, trello:<id> for Trello. The result line posts as a comment. Match on ID, move the payload: that's every integration, mechanically.

Example 2

// Mapping: a test is linked when its title carries the tracker's key —
//   Jira:   [PROJ-123] anywhere in the title
//   Trello: trello:<cardShortId> in the title
const jira = r.title.match(/\b([A-Z][A-Z0-9]+-\d+)\b/);
const trello = r.title.match(/trello:([a-zA-Z0-9]+)/);
const line = `Automated regression — ${stamp}: ${r.status.toUpperCase()} — "${r.title}"`;
// …posts that line as a COMMENT on the issue/card, when --send + credentials are present.

From the module's full text.