Notes
What it is
JavaScript is the language of the web, and Node.js runs it outside the browser. TypeScript is JavaScript plus types, checked before the code runs, which catches typos and wrong arguments early, the way the Java compiler does. Playwright Test runs dot t s files directly, with no separate build step. To start, install the Node long term support version, then run npm init playwright at latest in an empty folder.
- JavaScript: the language of the web, runs in Node.js
- TypeScript: JavaScript + types checked by the compiler
- Playwright runs .ts test files directly, no build step
- install Node.js LTS
- npm init playwright@latest
Variables
Use const for values that never change, which is most of them, and let for ones that do, like a retry counter. Avoid the old var keyword. Types go after a colon: number, string, boolean. Often you can leave them out and TypeScript infers them, like var in Java. One important difference: number is one type for whole numbers and decimals, and it behaves like a double. So the money rule still applies: compare cents, not dollar decimals.
const url = "http://localhost:8080"; let retries = 0; retries++; const qty: number = 4; const code: string = "SAVE10"; const inStock: boolean = true; // number: one type for ints // AND decimals (like double)
Objects
In TypeScript you often create objects directly with curly braces, no class needed. An interface describes the shape of an object, its fields and types. Here a product has a sku, a name, a price in cents and an in stock flag, exactly like ShopRung's API returns. Declare the mug as a product and the compiler checks every field. Interfaces are how you type API responses in tests, so a typo like price cent is caught before the test runs.
interface Product {
sku: string;
name: string;
priceCents: number;
inStock: boolean;
}
const mug: Product = {
sku: "MG-201", name: "Green
Build Mug", priceCents: 1500,
inStock: true };
mug.priceCents // 1500 Functions
Functions can be written with the function keyword, or as arrow functions, which you will see everywhere in Playwright. Backticks make template strings, where dollar and curly braces insert a value, like Hi comma user's name. The money function turns cents into text the way ShopRung does: forty nine ninety nine for four thousand nine hundred ninety nine cents. Arrow functions are like Java lambdas, and they are what you pass to array methods.
function money(c: number): string {
return `$${Math.floor(c / 100)}.` +
`${String(c % 100)
.padStart(2, "0")}`;
}
const isCheap = (p: Product) =>
p.priceCents < 1000;
money(4999) // "$49.99"
`Hi, ${user.name}` // template Equality
One JavaScript trap. Double equals converts types before comparing, so zero equals an empty string and the text one equals the number one. Triple equals compares without conversion, which is what you almost always want. Always use triple equals and its opposite, not equals equals. JavaScript also has two kinds of nothing: undefined, a value that was never set, and null, a value set to nothing on purpose.
0 == "" // true (!) "1" == 1 // true (!) null == undefined // true 0 === "" // false "1" === 1 // false always === and !== undefined: never set null: set to "nothing"
Arrays
Arrays have methods that work like Java streams, without the stream call. Map transforms each item, filter keeps some, find returns the first match, every and some check conditions, and includes checks membership. One trap: sort with no argument sorts numbers as text, so always pass a compare function, a minus b, and copy the array first with three dots if you need to keep the original order.
const prices = [1500, 499, 12999]; prices.length // 3 prices.map(money) // ["$15.00","$4.99","$129.99"] prices.filter(c => c < 1000) // [499] prices.every(c => c > 0) // true prices.includes(499) // true [...prices].sort((a, b) => a - b) // [499, 1500, 12999]
async and await
Now the most important part. Every browser action, a click, a fill, a page load, talks to a browser running in another process, so it takes time. Each one returns a promise, a value that will arrive later. Write await before it, and your test waits for the action to finish before the next line. Forget the await, and the test races ahead before the click happens, which causes flaky tests. A function that uses await must be marked async.
// a click talks to a browser in
// another process: it takes time
await page.click("text=Search");
// forgetting await:
page.click("text=Search");
// test moves on before the
// click happens → flaky test
functions using await are
marked async A first test
Here is a first Playwright test, for ShopRung's rule that search is not case sensitive. Import test and expect. Name the test, and receive a page as a fixture. Go to the shop. Find the search box by its role and its label, search products, and type MUG in capitals. Press enter. Then expect the result count to have the text two products. The expect line waits and retries until it is true or times out, which you will learn properly in Part five.
import { test, expect } from
"@playwright/test";
test("search is not case-
sensitive", async ({ page }) => {
await page.goto("/"); // baseURL
await page.getByRole("searchbox", {
name: "Search products" }).fill("MUG");
await page.keyboard.press("Enter");
await expect(page
.getByTestId("result-count"))
.toHaveText("2 products"); Java vs TS
A quick translation table. Final becomes const. A type before the name becomes a type after a colon. Records and data classes often become interfaces. Lambdas use a fat arrow, equals and greater than instead of a thin one. Stream map becomes plain map. Equals becomes triple equals. At test becomes a test function call, and assert equals becomes expect to be. The ideas you learned in Java carry over almost one to one.
final int q = 4; → const q = 4;
String s → s: string
record / class → interface
p -> p.stock() → p => p.stock
.stream().map → .map
equals() → ===
void m() {} → async () => {}
@Test → test("...", ..)
assertEquals → expect(..).toBe Common mistakes
TypeScript mistakes in Playwright tests. A missing await, the number one cause of flaky tests. Double equals instead of triple. Sorting numbers without a compare function. Typing everything as any, which switches off the checks you came for. Money as decimals. Await inside for each, which does not wait; use a for of loop instead. And hard coded addresses; Playwright's config has a base URL setting.
- missing await (flaky!)
- == instead of ===
- sort() on numbers with no compare function
- any everywhere (no checks)
- money as decimals
- await inside forEach (use for...of)
- hard-coded URLs: use baseURL in the config
Say it like this
A favourite question: why do Playwright tests need await? Say: every Playwright action talks to the browser asynchronously and returns a promise. Await makes the test wait for it, so steps run in order. A missing await lets the test move on before the action finishes, which causes flaky failures. Add that a lint rule for floating promises catches missing awaits automatically. That answer shows you understand the tool, not just the syntax.
- "Every Playwright action talks
- to the browser asynchronously
- and returns a promise. await
- makes the test wait for it, so steps run in order. A missing await lets the test
- move on early, which causes
- flaky failures. Linters can
- flag floating promises."