So im pretty much used to always using classes when writing automation code (Using the Page object Model). However i've came across some PoM/Component sample code that im not really used to seeing. For example this header.ts
file is not what I am used to seeing:
import { Page, expect } from "@playwright/test";
export function Header(page: Page) {
const self = page.locator('header');
const input = self.getByPlaceholder('What needs to be done?');
const toggleAllButton = page.getByLabel('Mark all as complete');
const completeAll = () => toggleAllButton.check();
const uncompleteAll = () => toggleAllButton.uncheck();
const addTodo = async (text: string) => {
await input.fill(text);
await input.press('Enter');
};
return {
addTodo,
completeAll,
uncompleteAll,
expect: () => ({
...expect(self),
toAllowUncompleteAll: (allow = true) => expect(toggleAllButton).toBeChecked({ checked: allow }),
toHaveEmptyInput: () => expect(input).toBeEmpty()
})
};
}
Now this is using Playwright specifically, but the object/component model is similar. In classes you don't typically "return" anything, but here they are returning all the functions to be used elsewhere.
I guess my main question is:
- Why do we have to return the functions within here as opposed to a class once you create the instance object we don't have to return anything.
- Is there really any advantage to doing it this way vs a class? (Feels messier?)
- I don't under the
...expect(self)
and what that is doing. To be honest why isself
used here anyways? (Im not familiar with how self works in functions)