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.
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.
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.
this.mainHeading = page.locator("h1").first();From the module's full text.
await expect(this.page).toHaveTitle("Aoma AI Agency — Get Found. Miss Fewer Leads.");From the module's full text.
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.
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.
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.
test("[TC-001] HomePage loads with correct title and heading", async ({ page }) => {From the module's full text.
const po = new HomePage(page);From the module's full text.
await po.goto();From the module's full text.
await po.expectLoaded();From the module's full text.
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.
// 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.
constructor(page: Page) {
this.page = page;
this.mainHeading = page.locator("h1").first();
}From the module's full text.
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).
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
/** 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.
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.
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.
use: { baseURL, trace: "on", video: "on", screenshot: "only-on-failure" }From the module's full text.
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.
"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.)
"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, hasTouchFrom the module's full text.
projects: [ { name: "firefox · Desktop", use: { browserName: "firefox", … } },
{ name: "firefox · iPhone 15", use: { … } }, … ]From the module's full text.
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.
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.
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.
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.”
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.
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.
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.
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.
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.
// 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.
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.
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.
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 COMMENTFrom 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.
// 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.