From JavaScript to Playwright: Your First Automated Browser Tests
This is the lesson the whole course has been building towards. A Playwright test is ordinary JavaScript: modules, classes, async/await, destructuring, arrow functions, arrays and objects, with a library that drives a real browser. In this lesson you will see exactly which JavaScript features each line of a Playwright test uses (and which earlier lesson taught it), set up a Playwright project, write UI tests with a page object and an API test against a small demo shop, and read both passing and failing results. All output below comes from real runs of Playwright 1.65 with Google Chrome on Windows. After this lesson you are ready for the full Playwright TypeScript course on SQA Tools.
📖 What You’ll Learn: the JavaScript features used in every Playwright test, mapping DOM scripting to Playwright locators and actions, installing Playwright, the config file, writing tests with test and expect, fixtures (page, request) via destructuring, auto-waiting and web-first assertions, a page object class, an API test, running tests and reading the list reporter, reading a failure with expected, received and call log, and where to go next.
🧩 The JavaScript Inside Every Playwright Test
Here is a typical test, annotated with the JavaScript feature on each line and the module of this course that covers it:
📄 search.spec.js (annotated)
import { test, expect } from "@playwright/test"; // ES modules (Module 11)
test("search shows results", async ({ page }) => { // arrow function + async (4, 10), destructuring (6)
await page.goto("/shop"); // await a promise (10)
const search = page.getByRole("searchbox"); // const, objects and methods (2, 7)
await search.fill("usb"); // strings (5)
await search.press("Enter");
const items = page.locator(".product");
await expect(items).toHaveCount(3); // matchers like Jest/Vitest (14)
const names = await items.allTextContents(); // arrays (6)
expect(names.every((n) => n.toLowerCase().includes("usb"))).toBe(true); // every, arrow, includes (6)
});
| JavaScript skill | Where you use it in Playwright |
|---|---|
| async/await and promises | Every browser action and assertion returns a promise; forgetting await is the #1 bug |
| Destructuring | async ({ page, request }) => picks the fixtures a test needs |
| Classes and modules | Page objects, helpers, fixtures shared between test files |
| Arrays and objects | Test data, allTextContents() results, API JSON |
| Loops and template literals | Data-driven tests: for (const u of users) test(`login as ${u.role}`, ...) |
| Error handling | Reading failures, retries for flaky infrastructure, test.fail |
| Environment variables | Base URLs and secrets per environment |
| DOM knowledge | Choosing good locators, understanding events, debugging in DevTools |
⚠️ Watch out: A missing await before expect(locator).toHaveText(...) or page.click(...) means the test moves on before the step finishes. The test may pass without checking anything, or fail later with a confusing error. ESLint’s eslint-plugin-playwright catches it.
🔁 From DOM Scripting to Playwright
In Module 12 you automated a page from inside it. Playwright does the same jobs from outside the browser, with auto-waiting built in:
| Plain JavaScript in the page (Module 12) | Playwright |
|---|---|
document.querySelector("#user") | page.locator("#user") or better page.getByLabel("Username") |
| Find a button by its text | page.getByRole("button", { name: "Sign in" }) |
input.value = "x" + dispatch input/change events | await locator.fill("x") (real, trusted typing) |
button.click() (untrusted event) | await locator.click() (real mouse click, waits until clickable) |
Hand-written waitFor() polling | Built-in auto-waiting and await expect(locator).toHaveText(...) |
el.textContent | await locator.textContent() / toHaveText() |
fetch("/api/users") | await request.get("/api/users") |
localStorage.setItem(...) before load | page.addInitScript(...), storageState |
| One page, same origin, stops on navigation | Many pages, tabs, origins and browsers, across navigations |
⬇️ Setting Up a Playwright Project
The quickest start is the official initialiser, which asks a few questions and creates a config, an example test and a GitHub Actions workflow:
⌨️ Terminal
npm init playwright@latest
For this lesson the project was set up by hand, to show each piece. It tests a tiny demo shop (a login page and a users API) served by a Node.js script, using the Google Chrome already installed on the computer:
⌨️ Terminal
mkdir pw-demo && cd pw-demo
npm init -y
npm pkg set type=module
npm install -D @playwright/test
npx playwright --version
🖥️ Output
Version 1.65.1
📄 playwright.config.js
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
reporter: "list",
use: {
baseURL: "http://localhost:5500",
channel: "chrome", // use the installed Google Chrome
trace: "on-first-retry",
},
webServer: {
command: "node site/server.js",
url: "http://localhost:5500/login",
reuseExistingServer: true,
},
});
baseURLlets tests writepage.goto("/login")instead of full URLs (switch environments with an environment variable, Module 11).channel: "chrome"uses installed Chrome; without it, runnpx playwright installto download Chromium, Firefox and WebKit.webServerstarts the app before the tests and stops it afterwards.trace: "on-first-retry"records a full trace when a retried test fails.
📄 A Page Object and Three Tests
The page object (Module 13, design patterns) keeps the locators in one place. Notice the locators: label, role and accessible name, exactly the “find it like a user” approach from Module 12:
📄 pages/LoginPage.js
export class LoginPage {
constructor(page) {
this.page = page;
this.username = page.getByLabel("Username");
this.password = page.getByLabel("Password");
this.signIn = page.getByRole("button", { name: "Sign in" });
this.message = page.getByRole("status");
}
async goto() {
await this.page.goto("/login");
}
async login(user, pass) {
await this.username.fill(user);
await this.password.fill(pass);
await this.signIn.click();
}
}
Two UI tests and one API test. The page and request parameters are fixtures: Playwright creates a fresh browser page (isolated cookies and storage) or an HTTP client for each test, and you pick them by destructuring:
📄 tests/login.spec.js
import { test, expect } from "@playwright/test";
import { LoginPage } from "../pages/LoginPage.js";
test.describe("login", () => {
test("valid user sees a welcome message", async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login("qa_user", "Test#123");
await expect(loginPage.message).toHaveText("Welcome, qa_user!"); // waits for the 300 ms API call
});
test("wrong password shows an error", async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login("qa_user", "wrong");
await expect(loginPage.message).toHaveText("Invalid username or password");
});
});
test("users API returns two users", async ({ request }) => {
const res = await request.get("/api/users");
expect(res.ok()).toBeTruthy();
const users = await res.json();
expect(users).toHaveLength(2);
expect(users.map((u) => u.name)).toEqual(["Asha", "Ravi"]);
});
⌨️ Terminal
npx playwright test tests/login.spec.js
🖥️ Output (Windows terminal)
Running 3 tests using 1 worker
ok 1 tests\login.spec.js:5:3 › login › valid user sees a welcome message (884ms)
ok 2 tests\login.spec.js:12:3 › login › wrong password shows an error (845ms)
ok 3 tests\login.spec.js:20:1 › users API returns two users (44ms)
3 passed (4.3s)
The login request takes 300 ms, yet there is no waitForTimeout anywhere: toHaveText keeps re-checking the message until it matches or 5 seconds pass. This auto-waiting is what replaces the hand-written polling from the Module 12 automation lesson.
🔍 Reading a Failure
A failing test tells you what was expected, what was received, what Playwright tried, and where in your code it happened:
📄 tests/failing.spec.js
import { test, expect } from "@playwright/test";
test("page title (deliberately failing)", async ({ page }) => {
await page.goto("/login");
await expect(page).toHaveTitle("Login | SQA Shop");
});
⌨️ Terminal
npx playwright test tests/failing.spec.js
🖥️ Output (Windows terminal, divider lines shortened)
Running 1 test using 1 worker
x 1 tests\failing.spec.js:3:1 › page title (deliberately failing) (5.4s)
1) tests\failing.spec.js:3:1 › page title (deliberately failing) ──────────────────
Error: expect(page).toHaveTitle(expected) failed
Expected: "Login | SQA Shop"
Received: "Login | Demo Shop"
Timeout: 5000ms
Call log:
- Expect "toHaveTitle" with timeout 5000ms
14 × locator resolved to <html lang="en">…</html>
- unexpected value "Login | Demo Shop"
3 | test("page title (deliberately failing)", async ({ page }) => {
4 | await page.goto("/login");
> 5 | await expect(page).toHaveTitle("Login | SQA Shop");
| ^
6 | });
7 |
at C:\Users\you\pw-demo\tests\failing.spec.js:5:22
Error Context: test-results\failing-page-title-deliberately-failing-\error-context.md
1 failed
tests\failing.spec.js:3:1 › page title (deliberately failing) ──────────────────
- Expected / Received: the actual title is “Login | Demo Shop”: either the test is wrong or the app is.
- Timeout 5000ms and “14 ×”: Playwright re-checked the title 14 times over 5 seconds before failing, so this is not a timing problem.
- Code frame: the exact line, like the Jest and node:test failures in the previous lessons.
- Error Context and traces: extra files in
test-results/; with tracing on,npx playwright show-tracereplays every step with DOM snapshots and network calls.
🛠️ Everyday Playwright Commands
| Command | Does |
|---|---|
npx playwright test | Run all tests |
npx playwright test login | Run test files whose path contains “login” |
npx playwright test -g "wrong password" | Run tests whose title matches |
npx playwright test --headed | Show the browser while running |
npx playwright test --ui | Interactive UI mode with time-travel debugging |
npx playwright test --debug | Step through with the Playwright Inspector |
npx playwright codegen http://localhost:5500/login | Record actions and generate test code |
npx playwright show-report | Open the HTML report |
💡 Tip: codegen is a great way to discover good locators: click around and Playwright writes getByRole and getByLabel calls for you. Treat the generated code as a draft and refactor it into page objects.
🧪 Tester Scenario: Your Learning Path from Here
You now have the JavaScript foundation that Playwright, Cypress, WebdriverIO and Puppeteer all build on. A practical path:
- Rewrite three of your manual test cases as Playwright tests against a practice site (the SQA Tools automation practice page or the dummy shop apps).
- Move locators into page objects and test data into builders or JSON files.
- Add one API test per feature with the
requestfixture, and use API calls to set up UI tests. - Run the suite in GitHub Actions with traces on failure.
- Continue with the Playwright TypeScript course (115 lessons): TypeScript, fixtures, authentication, network mocking, visual testing, CI and framework design.
- Check yourself with the timed Playwright mock interviews.
TypeScript adds types on top of exactly the JavaScript you learned here; every concept in this course carries over unchanged.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Rewrite this DOM script as a Playwright test step: document.querySelector("#email").value = "qa@sqatools.in".
Show answer
await page.getByLabel("Email").fill("qa@sqatools.in");
// or, if there is no label: await page.locator("#email").fill("qa@sqatools.in");fill focuses the field, clears it and types like a user, firing the input events that a plain value assignment does not.
Q2. Which fixture would you destructure for a pure API test, and which for a UI test?
Show answer
async ({ request }) => { ... } for API tests (an HTTP client with the config’s baseURL), and async ({ page }) => { ... } for UI tests (a fresh browser page in its own context). A test can take both: async ({ page, request }) =>.
Q3. Find the bug in this test.
test("shows welcome", async ({ page }) => {
await page.goto("/login");
page.getByRole("button", { name: "Sign in" }).click();
expect(page.getByRole("status")).toHaveText("Welcome");
});Show answer
Both the click() and the expect(...).toHaveText() are missing await. The test ends before the click happens and the assertion is never awaited, so it can pass without checking anything. Add await before both lines.
Q4. Write a data-driven Playwright test that tries three wrong passwords and expects the error message each time.
Show answer
for (const password of ["", "wrong", "Test#1234"]) {
test(`rejects password "${password}"`, async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login("qa_user", password);
await expect(loginPage.message).toHaveText("Invalid username or password");
});
}Q5. Add a method expectWelcome(name) to the LoginPage class.
Show answer
import { expect } from "@playwright/test";
// inside class LoginPage
async expectWelcome(name) {
await expect(this.message).toHaveText(`Welcome, ${name}!`);
}Keep such helpers clearly named (expect...) so readers know the method asserts something.
Q6. The failure output says “Received: Login | Demo Shop” after 14 checks over 5 seconds. Is this a timing problem? What do you do next?
Show answer
No. The title was stable and simply different from the expectation for the whole 5 seconds, so a longer timeout would not help. Decide whether the requirement or the test is wrong: check the specification, and either fix the expected value or report the title as a bug.
🧠 MCQ Quiz: From JavaScript to Playwright
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which JavaScript feature is needed before every Playwright action and assertion?Answer: await. They all return promises.
- What does
async ({ page }) =>use to get the page fixture?Answer: Object destructuring. Playwright passes an object of fixtures. - Which locator style does Playwright recommend first?Answer: getByRole / getByLabel (user-facing). They survive layout changes.
- What replaces hand-written polling from in-page scripts?Answer: Auto-waiting and web-first assertions. toHaveText retries until it matches or times out.
- What does the request fixture do?Answer: Sends HTTP requests for API tests. It uses the baseURL from the config.
- What does
baseURLin the config allow?Answer: page.goto(“/login”) with a relative path. Change environments in one place. - Which command opens the interactive UI mode?Answer: npx playwright test –ui. Great for debugging and exploring.
- What does “14 × locator resolved … unexpected value” in a failure mean?Answer: Playwright re-checked 14 times and the value never matched. It is not a timing issue.
- Which tool records your clicks and generates test code?Answer: npx playwright codegen. Refactor the output into page objects.
- Why is a page object useful?Answer: Locators and actions live in one place, so UI changes are fixed once. Covered in the design patterns lesson.
💼 Interview Questions and Answers
Q1. What JavaScript concepts are most important for writing Playwright tests?
Promises and async/await (every action is asynchronous), modules and classes (page objects, fixtures, helpers), destructuring (fixtures), arrays and objects (test data and API responses), template literals and loops (data-driven tests), error handling, environment variables for configuration, and a solid understanding of the DOM and events to choose good locators and debug failures.
Q2. How does Playwright avoid flaky waits?
Actions auto-wait for the element to be attached, visible, stable, enabled and able to receive events before acting. Web-first assertions such as toHaveText and toBeVisible retry until they pass or time out. Combined with user-facing locators and isolated browser contexts per test, this removes most of the need for manual sleeps.
Q3. What is the difference between a unit test (Jest/Vitest/node:test) and a Playwright test?
A unit test calls a function directly in Node.js, in milliseconds, with dependencies mocked. A Playwright test drives a real browser (or real HTTP calls) against a running application, checking the behaviour a user sees across the whole stack. Unit tests are many and fast; Playwright end-to-end tests are fewer, slower and verify that everything works together.
Q4. How would you structure a new Playwright project?
A config with baseURL from environment variables, projects for the browsers needed and traces on retry; tests/ grouped by feature; pages/ for page objects; fixtures for logged-in states (storageState) and shared setup; test-data/ with builders; API helpers for setup and clean-up; ESLint with the Playwright plugin; and a CI workflow that runs npm ci, installs browsers, runs tests and uploads the HTML report.
❓ Frequently Asked Questions
🤔 Should I learn Playwright with JavaScript or TypeScript?
Either works, and the APIs are identical. TypeScript adds autocomplete and catches mistakes earlier, so most teams use it; the Playwright course on SQA Tools uses TypeScript and builds directly on this JavaScript course.
🤔 Do I need to install browsers separately?
Run npx playwright install to download Playwright’s Chromium, Firefox and WebKit builds (add --with-deps on Linux CI). Alternatively use an installed browser with channel: "chrome" or "msedge".
🤔 Can Playwright test APIs without a browser?
Yes. The request fixture (or request.newContext()) sends HTTP requests directly, and tests that only use it never start a browser.
🤔 Is Playwright better than Selenium or Cypress?
Each has strengths. Playwright offers auto-waiting, multiple browsers including WebKit, multi-tab and multi-origin support, API testing, tracing and parallel runs out of the box, which is why many teams choose it for new projects.
🏁 Summary
- A Playwright test is plain JavaScript: modules, async/await, destructuring, classes, arrays and objects.
- Playwright replaces in-page DOM scripting with locators, trusted actions and built-in auto-waiting.
- A project needs @playwright/test, a config with baseURL (and optionally webServer), tests and page objects.
- Use the page fixture for UI tests and the request fixture for API tests; await every action and assertion.
- Read failures through Expected, Received, the call log and traces; continue with the Playwright TypeScript course.
Next, continue with Lesson 72: Project: To-Do App. This completes Module 14. Module 15 puts everything together in three projects: a browser to-do app, a Node.js CLI and an API checker.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in