What is a class in JavaScript, and why do test frameworks use them?
Written by Jatin Thacker, Automation Architect · Updated
This answer is one piece of Chapter 7: Classes and Modules.
- JavaScript Classes & OOP
- Why This Chapter Is Here: Page Objects Are Just Classes
- Modules: require() vs import/export
- Build: Your First Page Object
- Practice and interview questions: Classes, OOP & Modules
Most tests on a large team touch the same few pages. If every test writes its own locators, one change to the catalogue markup breaks forty files. A class lets you write them once.
In the example, CatalogPage is a page object. The constructor runs when you write new CatalogPage(page). It stores the Playwright page on this.page and builds the cartTotal locator once. this is the object being created, so every method can reach both.
open() and addToCart(sku) are methods. addToCart hides how a product is found: a template literal builds article[data-sku="${sku}"], then it clicks Add to cart inside that card. The test itself reads as steps: open the catalogue, add the grinder, add the kettle, check the total is ₹16,190.
Two things to keep in mind. Methods that drive the page are async, so the test must await each call. And a class body is always in strict mode, so passing catalog.addToCart around on its own, without its object, loses this and fails with a TypeError. Call it as catalog.addToCart(...).
The assertion stays in the test, not hidden in the class, so a reader sees what is being checked.
import { test, expect } from '@playwright/test';
class CatalogPage {
constructor(page) {
this.page = page;
this.cartTotal = page.getByTestId('cart-total');
}
async open() {
await this.page.goto('/catalog.html?mock=static&seed=42&autologin=1');
}
async addToCart(sku) {
await this.page
.locator(`article[data-sku="${sku}"]`)
.getByRole('button', { name: 'Add to cart' })
.click();
}
}
test('a page object adds two products', async ({ page }) => {
const catalog = new CatalogPage(page);
await catalog.open();
await catalog.addToCart('MRD-1003');
await catalog.addToCart('MRD-1001');
await expect(catalog.cartTotal).toHaveText('₹16,190');
});1 passed (2.6s)
page in its constructor?Practised in the full course: the drill this, lost in a callback.
See the chapterRelated questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free