playwright-elements
v1.16.0
Published
This is Playwright extension.
Downloads
1,753
Readme
Playwright-elements
Playwright elements helps you create reusable components with child elements and methods that can be called in chains. It reduces the amount of code in your page objects or allows you to work without page objects entirely.
Playwright-elements makes it easy to represent a web component's tree structure, where each component can have multiple descendants, and all elements within the tree inherit the Locator API. Each element can call both descendant elements and methods from the Locator API, allowing you to build a chain of calls involving elements and synchronous methods.
Installation: npm install -D playwright-elements
IMPORTANT: playwright elements is not standalone framework, it requires:
- v1.5:
@playwright/test >= 1.27.x
to added to project. - v1.6:
@playwright/test >= 1.33.x
to added to project. - v1.8:
@playwright/test >= 1.34.x
to added to project. - v1.9:
@playwright/test >= 1.38.x
to added to project. - v1.10:
@playwright/test >= 1.40.x
to added to project. - v1.13:
@playwright/test >= 1.42.x
to added to project. - v1.15:
@playwright/test >= 1.44.x
to added to project.
- Get started
- Web element
- Get by methods
- Sub elements
- Direct child
- Expect
- Extended Expect
- Locator and underscore
- With methods
- Get parent
- Build in selector helpers
- And
- Has
- Has not
- Has text
- Has not text
- Get element by index
- Strict mode
- Content Frame and Owner
- Clone
- Lists of WebElements
- Add handler
- Remove handler
- Actions
- All inner texts
- All text contents
- Blur
- Bounding box
- Check
- Clear
- Click
- Count
- Double click
- Dispatch event
- Drag to
- Fill
- Focus
- Get attribute
- Highlight
- Hover
- Inner HTML
- Inner text
- Input value
- Is checked
- Is disabled
- Is editable
- Is enabled
- Is hidden
- Is visible
- Press
- Screenshot
- Scroll into view if needed
- Select option
- Select text
- Set checked
- Set input files
- Tap
- Text content
- Press sequentially
- Uncheck
- Wait for
- How to extend WebElement
- Playwright elements fixtures
- Build page object
- Browser instance
- Use page
Get started
You don't need to pass the instance of page into your page object.
./pages/index.ts
import { $ } from 'playwright-elements';
export class MainPage {
readonly header = $('.navbar');
}
Each element created by the $ function returns an instance of WebElement, so the code may look like this:
./pages/index.ts
import { $, WebElement } from 'playwright-elements';
export class MainPage {
readonly header: WebElement = $('.navbar');
}
The $ function is just a shortcut for new WebElement('.navbar');
Each WebElement can have sub-elements, and child elements can have sub-elements as well. subElements({logo: $('.navbar__title')}) or with({logo: $('.navbar__title')}) returns type intersection.
./pages/index.ts
import { $, WebElement } from 'playwright-elements';
type Header = WebElement & { logo: WebElement }
export class MainPage {
readonly header: Header = $('.navbar')
.with({
logo: $('.navbar__title'),
githubLogo: $('a[aria-label="GitHub repository"]')
});
}
Several elements deep structure:
./pages/index.ts
import { $, WebElement } from 'playwright-elements';
type Table = WebElement & { thead: Webelement }
export class MainPage {
readonly table = $('table')
.with({
columnHeaders: $('thead td'),
rows: $('tbody tr')
.with({
cells: $('td')
})
});
}
Sub elements and custom methods:
./pages/index.ts
import { $, WebElement } from 'playwright-elements';
type Table = WebElement & { thead: Webelement }
export class MainPage {
readonly table = $('table')
.with({
columnHeaders: $('thead td'),
rows: $('tbody tr')
.with({
cells: $('td')
}),
async someCustomMethod(this: WebElement) {
//...
}
});
}
Type-Safe Fixture Setup:
./fixtures.ts
import { test as baseTest, buildPageObject, PageObject } from 'playwright-elements';
import { createIndexFile } from '../src/index';
import * as pageObjectModule from './pages';
// Generate an index files recursively in the specified folder or use cli interface.
generateIndexFile('./page.object');
type TestFixtures = { pageObject: PageObject<typeof pageObjectModule> };
export const test = baseTest.extend({
page: [async ({}, use) => {
await use(buildPageObject(pageObjectModule));
}, { scope: 'test' }],
});
You can generate index file via CLI Generate index file.
Elements like tables can be called in a chain with different filters to narrow down target inner elements for assertions or actions.
Usage in test:
./test.ts
import { test } from './fixtures'
test.describe('Invocation chain example', () => {
test('test', async ({ page }) => {
await page.table.columnHeaders.expect().toHaveText(['ID', 'Name', 'Status']);
await page.table.rows.hasText('Justin').cells.expect().toHaveText(['123', 'Justin', 'Single']);
});
});
Usage with playwright-test
Playwright elements provides you with extended test annotation which includes goto and usePage fixture and access to playwright expect methods via expect() function
playwright.config.ts
:
import { devices, PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
baseURL: 'https://playwright.dev',
}
};
export default config;
Pay attention that usage of buildPageObject
method to return pages in fixture is not mandatory.
import { test } from 'playwright-elements';
import { MainPage } from 'page.object'
test.describe('Goto fixure example', () => {
test('expect positive', async ({ goto }) => {
await goto();
const mainPage = new MainPage(); // Your page object is imdependent from page instance and from bieng returned from fixtures
await mainPage.header.logo.expect().toBeVisible();
await mainPage.header.logo.expect().toHaveText('Playwright');
})
})
BrowserInstance
will automatically bring to front and switch to opened tab.
import { test, $, BrowserInstance, expect } from 'playwright-elements';
test.describe('Playwright test integration', () => {
test('Tab swith example', async () => {
await goto();
const mainPage = new MainPage();
await expect(BrowserInstance.currentPage).toHaveURL('https://playwright.dev');
await mainPage.header.githubLogo.click();
await expect(BrowserInstance.currentPage).toHaveURL('https://github.com/microsoft/playwright');
await BrowserInstance.switchToPreviousTab();
await expect(BrowserInstance.currentPage).toHaveURL('https://playwright.dev');
await BrowserInstance.switchToTabByIndex(1);
await expect(BrowserInstance.currentPage).toHaveURL('https://github.com/microsoft/playwright');
})
})
Web element
WebElement class is a wrapper on playwright Locator. It was created to allow creation of complex web components which support multiple levels sub elements with ability to add custom methods.
If you use @playwright/test
see: Playwright elements fixtures.
In case you use any another test runner see: Browser Instance.
Get by methods
Next methods allow easy way to create locators in complex components.
Example:
import { $getByTestId, $getByPlaceholder, $getByTitle, WebElement } from "playwright-elements";
class MainPage {
readonly form = $getByTestId(`login-form`)
.subElements({
loginField: $getByPlaceholder('Email or phonenumber'),
passwordField: $getByPlaceholder('Password'),
submitButton: $getByTitle('Login')
})
}
Sub elements
Simple child element creation
import { $, $getByTestId } from "playwright-elements";
class MainPage {
readonly header = $(`.header`);
readonly avatar = header.$getByTestId('user-img')
}
Complex component creation:
import { $ } from "playwright-elements";
class MainPage {
readonly header = $(`.header`)
.subElements({
userInfoSection: $(`.userInfo`)
.subElements({
firstName: $(`.first-name`),
lastName: $(`.last-name`),
avatar: $(`.userImage`)
})
})
}
Allows chain selectors:
import { $ } from "playwright-elements";
class MainPage {
readonly element = $getByTestId('parentTestId').$('.child')
.subElements({
subChild: $getByTestId('subChildId').$('.subChild2'),
});
}
Expect
Web element has methods expect()
and softExpect()
which allows access to
playwright assert library.
Please pay attention that Locator passed to native expect method under the hood
that's why autocomplete works only for default locator matchers but pay attention that it allows you to call
custom matchers without errors.
test(`header should contain user info`, async () => {
const mainPage = new MainPage();
await mainPage.header.userInfoSection.firstName.softExpect().toHaveText(`Bob`);
await mainPage.header.userInfoSection.lastName.softExpect().toHaveText(`Automation`);
await mainPage.header.userInfoSection.avatar.expect().toBeVisible();
})
Extended Expect
Web element allows users to use custom matchers (even if you do not reassign extended expect explicitly), they can be called without any errors but autocomplete features may not work. Related playwright docs: https://playwright.dev/docs/next/test-assertions#add-custom-matchers-using-expectextend
import { Locator } from '@playwright/test';
import { expect, $, test } from 'playwright-elements';
expect.extend({
async toHaveAriaLabel(locator: Locator, expected: string, options?: { timeout?: number }) {
...
}
});
test.describe(() => {
test(`use custom expect matcher example`, async ({ goto }) => {
await goto('/');
const header = $(`.navbar`);
await header.expect().toHaveAriaLabel('Main');
})
})
In case you have plenty of custom expect matchers, and you want to make autocomplete work you need to extend web element and add additional expect method:
customWebElement.ts
import { WebElement, expect } from 'playwright-elements';
const extendedExpect = expect.extend(customMatchers);
class CustomWebElement extends WebElement {
public customExpect(message?: string) {
return extendedExpect(this.locator, message);
}
}
export function $(selector: string): CustomWebElement {
return new CustomWebElement(selector);
}
someTest.test.ts
import { test } from 'playwright-elements';
import { $ } from './customWebElement';
test(`custom expect matcher`, async ({ goto }) => {
await goto('/');
const header = $(`.navbar`);
await header.customExpect().toHaveAriaLabel('Main');
})
Now autocomplete works but in case you want explicitly define return type for customExpect method you can use utility type (ReturnType), this will guarantee correct autocomplete:
import { Locator } from '@playwright/test';
import { WebElement, expect } from 'playwright-elements';
const extendedExpect = expect.extend(customMatchers);
class CustomWebElement extends WebElement {
public customExpect(message?: string): ReturnType<typeof extendedExpect<Locator>> {
return extendedExpect(this.locator, message);
}
}
Locator and underscore
Web element has getters locator
and _
both return instance of Locator.
import { test } from 'playwright-elements';
import { MainPage } from 'main.page';
test.describe('Playwright test integration', () => {
test('expect positive', async () => {
const mainPage = new MainPage();
// Both lines do the same.
await mainPage.header.logo.locator.click();
await mainPage.header.logo._.click();
})
})
With methods
Allows to add custom methods to web elements.
import { $, WebElement } from "playwright-elements";
class MainPage {
readonly header = $(`.header`)
.subElements({
humburgerButton: $(`.hButton`),
menu: $(`.menu`)
.subElements({
item: $(`.menu-item`)
.withMethods({
async hoverAndClick(this: WebElement) {
await this.locator.hover();
await this._.click();
}
})
})
})
}
hoverAndClick
method now can be used on item element. Please pay attention that to access web element
default methods inside additional method declaration is used fake this: WebElement
pointer.
test(`user can open documentation`, async () => {
const mainPage = new MainPage();
await mainPage.header.menu.item.withText(`Documentation`).hoverAndClick();
})
With
This method combines subElements
and withMethods
in one method,
it allows you to create sub elements and add custom methods in one body.
import { $, WebElement } from "playwright-elements";
class MainPage {
readonly header = $(`.header`)
.with({
humburgerButton: $(`.hButton`),
menu: $(`.menu`)
.with({
item: $(`.menu-item`),
async expand(this: WebElement) {
await this.locator.hover();
await this._.click();
}
}),
async someCustomHeaderMethod(this: WebElement) {
//...
}
})
}
Get parent
parent<T>(this: WebElement): WebElement & T
method allows get parent and extend it's type.
Allows to access parent element.
import { $, WebElement } from "playwright-elements";
const header = $('.header')
.subElements({
logo: $('.log-img'),
logIn : $('#log-in')
});
header.logo.parent(); // allows to access parent web element
header.login.parent<{ logo: WebElement }>(); // also parent method accepts generic with type
It allows users to access sibling elements inside custom methods.
import { $, WebElement } from "playwright-elements";
const header = $('.header')
.subElements({
userIcon: $('#icon'),
logIn : $('#log-in')
.withMethods({
async goToLoginPage(this: WebElement) {
await this.parent<userIcon>().userIcon.hover();
await this.click();
}
})
});
Despite strict return type parent<T>(this: WebElement): WebElement & T
when element has not parent it returns undefined
.
It allows avoid optional chaining each time you need call anything from parent
but still implement if condition.
import { $, WebElement } from "playwright-elements";
test(`get parent`, () => {
const header = $('.header');
header.parent; // undefined
})
Build in selector helpers
And
Method and<T extends WebElement, R extends WebElement>(this: R, element: string | T): R
helps to use multiple
selectors to find one element.
import { $ } from "playwright-elements";
const button = $('button').and('[title=Subscribe]');
or
import { $getByRole, $getByTitle } from "playwright-elements";
const button = $getByRole('button').and($getByTitle('Subscribe'));
Has
Method has(selector: string | WebElement)
helps to find elements with specific child.
Based on selector:
import { $ } from "playwright-elements";
class MainPage {
readonly fieldRows = $(`.field-row`).has(`input.enabled`);
}
Based on WebElement:
import { $ } from "playwright-elements";
class MainPage {
private readonly enabledEnputs = $(`input.enabled`);
readonly fieldRows = $(`.field-row`).has(enabledEnputs);
}
Has not
Method hasNot(selector: string | WebElement)
helps to find elements without specific child.
Based on selector:
import { $ } from "playwright-elements";
class MainPage {
readonly fieldRows = $(`.field-row`).hasNot(`input.disabled`);
}
Based on WebElement:
import { $ } from "playwright-elements";
class MainPage {
private readonly enabledEnputs = $(`input.disabled`);
readonly fieldRows = $(`.field-row`).hasNot(enabledEnputs);
}
Has text
Method hasText(text: string | RegExp)
helps to find elements with specific text or child with text.
Based on text:
import { $ } from "playwright-elements";
class MainPage {
readonly paragraph = $(`p`).hasText(`Some text:`);
}
Based on RegExp:
import { $ } from "playwright-elements";
class MainPage {
readonly paragraph = $(`.p`).hasText(/Some text:/);
}
Has not text
Method hasNotText(text: string | RegExp)
helps to find elements without specific text or child with text.
Based on text:
import { $ } from "playwright-elements";
class MainPage {
readonly paragraph = $(`p`).hasNotText(`Some text`);
}
Based on RegExp:
import { $ } from "playwright-elements";
class MainPage {
readonly paragraph = $(`.p`).hasNotText(/Some text/);
}
Methods has, hasNot, hasText and HasNotText can be combined in chain.
import { $ } from "playwright-elements";
class MainPage {
readonly fieldRows = $(`.field-row`).hasText(`Title:`).has(`input.enabled`);
}
Get element by index
Method nth(index: number)
will call from current locator in runtime locator(...).nth(index)
and methods first()
calls locator(...).nth(0)
, last()
calls locator(...).nth(-1)
playwright docs about nth()
Strict mode
By default, Locator is in strict mode, docs.
So in case you want to ignore it this rule you can first()
, last()
or nth(index: number)
methods to point in particular element by index:
import {$} from "playwright-elements";
class MainPage {
readonly errors = $(`.error-message`);
}
test(`find error by text`, async () => {
const mainPage = new MainPage();
await mainPage.errors.first().expect().toHaveText("Incorrect First name");
await mainPage.errors.last().expect().toHaveText("Incorrect paasword");
})
Content Frame and Owner
When you need to use FrameLocator
as WebElement
method contentFrame()
will use frame locator page.frameLocator('#my-frame')
.
And in case you need to switch back use method owner()
.
Behind the scene playwright-elements will build next expression:
page.frameLocator('#my-frame').locator('.header')
import {$} from "playwright-elements";
class MainPage {
readonly iframe = $(`#my-frame`).contentFrame()
.subElements({
header: $(`.header`)
});
}
test(`find error by text`, async () => {
const mainPage = new MainPage();
await mainPage.iframe.header.expec().toBeVisible();
await mainPage.iframe.owner(); // will use locator instead of frame locator.
})
Clone
clone<T extends WebElement>(this: T, options?: {
selector?: string
hasLocator?: string,
hasNotLocator?: string,
hasText?: string | RegExp,
hasNotText?: string | RegExp,
nth?: number
}): T
method allows to clone any web element and override it's selector and filter properties.
import { $ } from 'playwright-elements';
const originElement = $('.button').hasText('Submit').hasNotText('Ok');
const owerridenElement = originElement.clone({ selector: 'input[type=button]' }); // will still hasText=Submit and haasNotTet=Ok but will use another selector.
Add handler
addHandler<T extends WebElement>(this: T, handler: (element: T) => Promise<any>, options?: { noWaitAfter?: boolean, times?: number }): Promise<void>
method is simple port of addLocatorHandler function.
Remove handler
removeHandler(): Promise<void>
method is simple port of removeLocatorHandler function.
Actions
Web elements provide users with direct access to common actions from playwright locator class.
But in case you will need to use such methods as evaluate
, evaluateAll
, locator.filtrer
, locator.all
or any
another method from locator which you will not be abel find in list below please use getter [locator] or [_]
All inner texts
$('selector').allInnerTexts();
calls: allInnerTexts().
All text contents
$('selector').allTextContents();
calls: allTextContents().
Blur
$('selector').blur(options?);
calls: blur().
Bounding box
$('selector').boundingBox(options?);
calls: boundingBox().
Check
$('selector').check(options?);
calls: check().
Clear
$('selector').clear(options?);
calls: clear().
Click
$('selector').click(options?);
calls: click().
Count
$('selector').count();
calls: count().
Double click
$('selector').dblclick(options?);
calls: dblclick().
Dispatch event
$('selector').dispatchEvent(type, eventInit?, options?);
calls: dispatchEvent().
Drag to
$('selector').dragTo(target, options?);
calls: dragTo().
Fill
$('selector').fill(value, options?);
calls: fill().
Focus
$('selector').focus(options?);
calls: focus().
Get attribute
$('selector').getAttribute(name, options?);
calls: getAttribute().
Highlight
$('selector').highlight();
calls: highlight().
Hover
$('selector').hover(options?);
calls: hover().
Inner HTML
$('selector').innerHTML(options?);
calls: innerHTML().
Inner text
$('selector').innerText(options?);
calls: innerText().
Input value
$('selector').inputValue(options?);
calls: inputValue().
Is checked
$('selector').isChecked(options?);
calls: isChecked().
Is disabled
$('selector').isDisabled(options?);
calls: isDisabled().
Is editable
$('selector').isEditable(options?);
calls: isEditable().
Is enabled
$('selector').isEnabled(options?);
calls: isEnabled().
Is hidden
$('selector').isHidden();
calls: isHidden().
Is visible
$('selector').isVisible(options?);
calls: isVisible().
Press
$('selector').press(key, options?);
calls: press().
Screenshot
$('selector').screenshot(options?);
calls: screenshot().
Scroll into view if needed
$('selector').scrollIntoViewIfNeeded(options?);
calls: scrollIntoViewIfNeeded().
Select option
$('selector').selectOption(values, options?);
calls: selectOption().
Select text
$('selector').selectText(options?);
calls: selectText().
Set checked
$('selector').setChecked(checked, options?);
calls: setChecked().
Set input files
$('selector').setInputFiles(files, options?);
calls: setInputFiles().
Tap
$('selector').tap(options?);
calls: tap().
Text content
$('selector').textContent(options?);
calls: textContent().
Press sequentially
$('selector').pressSequentially(text, options?);
calls: pressSequentially().
Uncheck
$('selector').uncheck(options?);
calls: uncheck().
Wait for
$('selector').waitFor(options?);
calls: waitFor().
Lists of WebElements
Suite of methods to work with arrays of elements.
Get all
Method getAll<T extends WebElement>(this: T): Promise<T[]>
returns list of Web elements without any waiting
based on count of elements in particular moment of time.
import { $, WebElement } from 'playwright-elements';
test(`list of web elements`, async () => {
const elements: WebElement[] = $(`li`).getAll();
})
Async for each
Method asyncForEach(action: (element: T) => unknown | Promise<unknown>)): Promise<void>
works with sync and async functions in callbacks and returns promise, so you can await on execution.
Inside asyncForEach all callbacks are collected in to array and wrapped in
Promise.all([action(element), action(element)...]). This approach is suitable when you need
to collect for example text from elements or perform soft assert. But such actions like click, hover, fill,
actually any interactions with web elements will not work stable inside this loop. For actions is better to use
syncForEach
.
test(`asyncForEach example`, async () => {
const elements = $(`li`);
const elementsTexts: (string | null)[] = [];
await elements.asyncForEach(async (e) => elementsTexts.push(await e.locator.textContent()));
})
Sync for each
Method syncForEach<T extends WebElement>(this: T, action: (element: T) => unknown | Promise<unknown>): Promise<void>
works with sync and async functions in callbacks and returns promise, so you can await on execution.
Inside syncForEach each action awaited for (const ele of list) { await action(ele); }
.
This approach is suitable when you need to perform the same action for each element one by one.
test(`syncForEach example`, async () => {
const elements = $(`input`);
await elements.syncForEach(async (e) => await e.locator.type(`abc`));
})
Map
Method map<T extends WebElement, R>(this: T, item: (element: T) => R | Promise<R>): Promise<Awaited<R[]>>
works with sync and async functions in callbacks and returns list of extracted values.
test(`map example`, async () => {
const elements = $(`li`);
const texts: (string | null)[] = await elements.map(async (e) => await e.locator.textContent());
})
Filter elements
Method filterElements<T extends WebElement>(this: T, predicate: (element: T) => boolean | Promise<boolean>): Promise<T[]>
works with sync and async functions in callbacks and returns sub list of elements for with predicate returned true.
test(`filter elements example`, async () => {
const elements = $(`input`);
const enabledInputs = await elements.filterElements(async (e) => await e.locator.isEnabled());
})
Filter
Method filter<T extends WebElement, R extends WebElement>(this: T, options: { has?: string | T, hasNot?: string | T: hasText?: string, hasNotText?: string }): R
This method narrows existing locator according to the options, for example filters by text.
test(`filter elements example`, async () => {
const elements = $(`div`);
const filtered = elements.filter({ has: '#id', hasNot: '.hidden', hasText: 'Visible target', hasNotText: 'Visible wrong target' });
})
How to extend Web Element
In case you want to create custom web element.
Extend base class, create init function:
import { WebElement } from 'playwright-elements';
class Field extends WebElement {
public async set(this: WebElement, value: string) {
await this.fill("");
await this.type(value, { delay: 50 });
}
}
export function $field(selector: string): Input {
return new Field(selector);
}
or static factory function:
import { WebElement } from "playwright-elements";
export class Field extends WebElement {
public async set(this: WebElement, value: string) {
await this.fill("");
await this.type(value, { delay: 50 });
}
static $(selector: string): Input {
return new Field(selector);
}
}
And use in your elements:
import { $ } from "playwright-elements";
import { Input } from "./field.element";
export class MissingControlOverviewPage {
readonly form = $(`.form`)
.subElements({
nameField: Input.$(`.name-field`),
});
}
or:
import { $ } from "playwright-elements";
import { $field } from "./field.element";
export class MissingControlOverviewPage {
readonly form = $(`.form`)
.subElements({
nameField: $field(`.name-field`),
});
}
Use page
usePage<T>(page: Page, callBack: () => Promise<T>): Promise<T>
this function allows to execute actions in specific context.
The most common use case for this function when user needs more than one BrowserContext in test.
Example:
import { test as baseTest, $, usePage } from 'playwright-elements';
type TestFixtures = { secondContextPage: Page };
const test = baseTest.extend<TestFixtures, {}>({
secondContextPage: [async ({ browser }, use) => {
const context = await browser.newContext();
const page = await context.newPage();
await use(page);
await context.close();
}, { scope: 'test' }]
});
test.describe('Two contexts', () => {
const testFixturesPage = new TestFixturesPage();
test('use two contexts', async ({ goto, secondContextPage }) => {
await Promise.all([goto('https://default.com'), secondContextPage.goto('https://url.com')]);
const customContextPromise = usePage(secondContextPage, async () => {
// All playwright-elements in this scope will use secondContextPage.
$('h1').softExpect().toHaveUrl('https://url.com');
});
// All playwright-elements in main scope will use default context started by playwright test.
const defaultContextPromise = $('h1').softExpect().toHaveUrl('https://default.com');
await Promise.all([defaultContextPromise, customContextPromise]);
});
});
Use page function can return value from callback:
test('usePage returns value', async ({ goto, page }) => {
await goto();
const text = await usePage<string>(page, async () => {
return $('h1').textContent();
});
expect(text).toEqual('Expected title');
});
Playwright elements fixtures
This documentation explains how to use playwright-elements
with @playwright/test
.
This lib extends default test
annotation with tree custom fixtures: goto
, initBrowserInstance
and usePage
.
One of them initBrowserInstance
, are auto fixture, so you do not need to call it explicitly to use.
Goto
goto
returns function from pure playwright.
Config:
import { devices, PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
baseURL: 'https://playwright.dev',
}
};
export default config;
Test:
import { test } from "playwright-elements";
test(`goto playwright docs`, async ({ goto }) => {
await goto('/docs/test-typescript'); // navigate you directly to https://playwright.dev/docs/test-typescript
})
or
import { test } from "playwright-elements";
test(`goto playwright docs`, async ({ goto }) => {
await goto(); // navigates to base url
})
also, you are able to pass options:
import { test } from "playwright-elements";
test(`goto playwright docs`, async ({ goto }) => {
await goto('/', { waitUntil: 'domcontentloaded' }); // navigates to base url
})
Init browser instance
initBrowserInstance
is auto fixture which returns void, and it's main purpose is to set currentPage,
currentContext and browser pointers.
Fixture use page
Just a representation of function Use page as fixture.
usePage
allows user to perform actions in another context. In case you need to use second tab
in the same context use BrowserInstance.swith
Use case:
type TestFixtures = { secondContextPage: Page, useSecondContext: <T>(callback: () => Promise<T>) => Promise<T> };
const test = baseTest.extend<TestFixtures>({
secondContextPage: [async ({ browser }, use) => {
const context = await browser.newContext();
const page = await context.newPage();
await use(page);
await context.close();
}, { scope: 'test' }],
useSecondContext: [async ({ secondContextPage }, use) => {
await use(<T>(callback: () => Promise<T>) => usePage<T>(secondContextPage, callback));
}, { scope: 'test' }]
});
test('example', async ({ goto, useSecondContext }) => {
await goto();
const text = await useSecondContext<string>(async () => {
await goto('/docs/test-fixtures');
return title.textContent();
});
expect(text).toEqual('Fixtures');
expect(await title.textContent()).toEqual('Playwright enables reliable end-to-end testing for modern web apps.')
});
Build page object
The buildPageObject utility automatically creates a strongly-typed page object instance from a module containing multiple page classes, providing full TypeScript autocompletion support in your tests.
Type-Safe Fixture Setup:
import { test as baseTest, buildPageObject, PageObject } from 'playwright-elements';
import * as pageObjectModule from './pages';
type TestFixtures = { pageObject: PageObject<typeof pageObjectModule> };
const test = baseTest.extend({
pageObject: [async ({}, use) => {
await use(buildPageObject(pageObjectModule));
}, { scope: 'test' }],
});
Page object
// pages/index.ts
export class HomePage {
welcome() {
return 'Welcome to homepage';
}
}
export class SettingsPage {
getSettings() {
// Implementation
}
}
Then use in your tests with full autocompletion:
test('navigation example', async ({ pageObject }) => {
// Full autocompletion for all pages and their methods
const welcomeMessage = pageObject.home.welcome();
await pageObject.settings.getSettings();
});
The pageObject fixture automatically includes all exported page classes, with properties matching their lowercase names: pageObject.home - instance of HomePage pageObject.settings - instance of SettingsPage This approach scales automatically as you add new page objects to your test suite, without requiring any changes to your test fixtures.
Build Page Object Options: suffix and lowerCaseFirst
The new buildPageObject feature not only instantiates all exported page classes automatically but also provides options to control how the keys (i.e., property names) are generated for each page object. Two important options are:
// Default behavior:
// suffix: 'Page', lowerCaseFirst: true
const pageObject1 = buildPageObject(pageObjectModule);
// Resulting keys:
pageObject1.home // → Instance of HomePage
pageObject1.settings // → Instance of SettingsPage
// Retain the full class name by not removing any suffix:
const pageObject2 = buildPageObject(pageObjectModule, { suffix: '' });
// Resulting keys:
pageObject2.homePage // → Instance of HomePage
pageObject2.settingsPage // → Instance of SettingsPage
// Remove suffix as usual but preserve original casing:
const pageObject3 = buildPageObject(pageObjectModule, { lowerCaseFirst: false });
// Resulting keys:
pageObject3.Home // → Instance of HomePage
pageObject3.Settings // → Instance of SettingsPage
Key Benefits of buildPageObject factory method.
- Automatically creates page object instances from all exported page classes
- Provides full TypeScript autocompletion for all page methods
- Eliminates need to manually update fixtures when adding new pages
- Maintains type safety across your entire test suite
Generate index file
CLI Interface
The index generator is also available as a standalone CLI tool. This provides a convenient way to generate (and optionally watch) index files without modifying your code, which is especially useful in CI/CD pipelines or during test environment setup for UI tests.
CLI Usage Examples:
Generate index file once:
npx generate-index ./src
Generate index files with watch mode enabled:
npx generate-index ./src --watch true
Generate index files with console logs:
npx generate-index ./src --cliLog true
Specify quote style (use double quotes, default value is single quotes):
npx generate-index ./src --quotes '"'
Programing interface
The generateIndexFile
function generates an index.ts
file in a specified folder.
It scans the folder for .ts
files (excluding index.ts) and creates export statements for each file.
This function is useful for automating the creation of centralized export files in TypeScript projects.
Parameters:
folder
(string): The directory where the index.ts file will be created.options
(Options, optional):cliLog
(boolean, default: false): Enables or disables logging to the console.quotes
( ' | ", default: ' ): Specifies whether to use single or double quotes in the generated export statements.watch
(boolean, optional, default: false): starts watchers on backgraund for each subdirectory.
Example Usage:
The function can be used in various contexts. For example, it can be called in a Playwright configuration file to dynamically generate an index.ts file before running tests.
import { test as baseTest, buildPageObject, PageObject, generateIndexFile } from 'playwright-elements';
import * as pageObjectModule from './pages';
// Generate an index files recursively in the specified folder
generateIndexFile('./page.object'); // one time generation
type TestFixtures = { pageObject: PageObject<typeof pageObjectModule> };
export const test = baseTest.extend({
page: [async ({}, use) => {
await use(buildPageObject(pageObjectModule));
}, { scope: 'test' }],
});
Watch mode usage example:
import { generateIndexFile } from '../src/index';
// Generate an index files recursively in the specified folder
const watchers = generateIndexFile('./page.object', { watch: true });
// you should close all watchers before process exit.
// Each nested directory with index file will have dedicated watcher
watchers.closeAll();
Before Generation:
testFolder/
├── file1.ts
├── file2.ts
└── nested/
├── nestedFile1.ts
After Generation:
testFolder/
├── index.ts // root level will include "export * from './nested'";
├── file1.ts
├── file2.ts
└── nested/
├── index.ts
├── nestedFile1.ts
Browser Instance
This object represents single-tone for Browser
, BrowserContext
and Page
.
It allows avoiding pass page
in your page object.
Browser name
BrowserName
is a simple enum with browser names you can install with npx playwright install
command.
See more in install browsers docs.
export enum BrowserName {
CHROMIUM = 'chromium',
CHROME = 'chrome',
CHROME_BETA = 'chrome-beta',
FIREFOX = 'firefox',
WEBKIT = 'webkit',
MSEDGE = 'msedge',
MSEDGE_BETA = 'msedge-beta',
MSEDGE_DEV = 'msedge-dev'
}
Start
start(browserName?: BrowserName, options?: LaunchOptions): Promise<Browser>
method starts new browser
and remembers it, see Getters and setters.
Args:
- BrowserName enum with possible browser names.
- LunchOptions is a playwright type.
Returns: Browser
Example:
import { BrowserName, BrowserInstance } from "playwright-elements";
async function useStart() {
await BrowserInstance.start(BrowserName.CHROME, {headless: fasle});
}
Start new context
startNewContext(options?: BrowserContextOptions): Promise<BrowserContext>
method starts browser context
and remembers it.
Args:
Returns: BrowserContext
Example:
import { BrowserName, BrowserInstance } from "playwright-elements";
import { devices } from 'playwright-core';
async function useStartNewContext() {
await BrowserInstance.start(BrowserName.CHROME, { headless: fasle });
await BrowserInstance.startNewContext({ ...devices['iPhone 13'] });
}
Start new page
startNewPage(options?: BrowserContextOptions): Promise<Page>
method starts new page or context and page
and remembers them.
Args:
- BrowserContextOptions methods has argument BrowserContextOptions but will use it only if you call this method when context is not started.
Returns: Page
Example:
import { BrowserName, BrowserInstance } from "playwright-elements";
import { devices } from 'playwright-core';
async function useStartNewPage() {
await BrowserInstance.start(BrowserName.CHROME, { headless: fasle });
await BrowserInstance.startNewContext({ ...devices['iPhone 13'] });
await BrowserInstance.startNewPage();
}
Or to achieve the same result:
import { BrowserName, BrowserInstance } from "playwright-elements";
import { devices } from 'playwright-core';
async function useStartNewPage() {
await BrowserInstance.start(BrowserName.CHROME, { headless: fasle });
await BrowserInstance.startNewPage({ ...devices['iPhone 13'] });
}
Close
close(): Promise<void>
method closes browser and removes pointers on Browser
, BrowserContext
and Page
.
Example:
import { BrowserName, BrowserInstance } from "playwright-elements";
import { devices } from 'playwright-core';
async function useClose() {
await BrowserInstance.start(BrowserName.CHROME, { headless: fasle });
await BrowserInstance.startNewPage({ ...devices['iPhone 13'] });
await BrowserInstance.close();
}
Getters and setters
get currentPage(): Pag
returns instance of Page
set currentPage(page: Page | undefined)
sets instance of page or undefined if you need to remove pointer.
get currentContext(): BrowserContext
returns instance of BrowserContext
set currentContext(context: BrowserContext | undefined)
sets instance of browser context or undefined if you need to remove pointer.
get browser(): Browser
returns instance of Browser
set browser(browser: Browser | undefined)
sets instance of browser or undefined if you need to remove pointer.
Examples:
Getters:
import { BrowserName, BrowserInstance } from "playwright-elements";
import { devices, Browser, BrowserContext, Page, BrowserContext } from 'playwright-core';
async function useGetters() {
await BrowserInstance.start(BrowserName.CHROME, {headless: fasle});
await BrowserInstance.startNewPage({...devices['iPhone 13']});
const browser: Browser = BrowserInstance.browser;
const context: BrowserContext = BrowserInstance.currentContext;
const page: Page = BrowserInstance.currentPage;
}
Setters:
import { BrowserInstance } from "playwright-elements";
import { webkit } from 'playwright-core';
async function useSetters() {
const browser = await webkit.launch();
const context = await browser.newContext();
const page = await context.newPage();
BrowserInstance.browser = browser;
BrowserInstance.currentContext = context;
BrowserInstance.currentPage = page;
}
Is mobile context
get isContextMobile(): boolean
to check if current context was set to mobile config
set isContextMobile(isMobile: boolean)
allow you to override default logic. By default, this setter is used
in initBrowserInstance auto fixture and just store isMobile
fixture state from playwright test.
import { test, BrowserInstance } from "playwright-elements";
import { devices } from "@playwright/test";
test.describe(`Mobile tests`, () => {
test.use({...devices['iPhone 13']})
test(`expect positive`, () => {
BrowserInstance.isContextMobile // returns true
})
})
test.describe(`Desktop tests`, () => {
test.use({...devices['Desktop Chrome']})
test(`expect positive`, () => {
BrowserInstance.isContextMobile // returns false
})
})
Builder like methods
withBrowser(browser: Browser): void
sets instance of browser.
withContext(context: BrowserContext): void
sets instances of browser context and browser.
withPage(page: Page): void
sets instances of page, browser context and browser.
Examples:
withBrowser sets only browser instance:
import { BrowserInstance } from "playwright-elements";
import { webkit } from 'playwright-core';
async function useWithBrowser() {
BrowserInstance.withBrowser(await webkit.launch());
const browser = BrowserInstance.browser;
}
withContext sets context and browser instances:
import { BrowserInstance } from "playwright-elements";
import { webkit } from 'playwright-core';
async function useWithBrowser() {
const browser = await webkit.launch();
const context = await browser.newContext();
BrowserInstance.withContext(browser);
const storedContext = BrowserInstance.currentContext;
const storedBrowser = BrowserInstance.browser;
}
withPage sets page, context and browser instances:
import { BrowserInstance } from "playwright-elements";
import { webkit } from 'playwright-core';
async function useWithBrowser() {
const browser = await webkit.launch();
const context = await browser.newContext();
const page = await context.newPage();
BrowserInstance.withPage(page);
const storedPage = BrowserInstance.currentPage;
const storedContext = BrowserInstance.currentContext;
const storedBrowser = BrowserInstance.browser;
}
Switch to previous tab
switchToPreviousTab(): Promise<void>
when new page is opened BrowserInstance
stores pointer on previous one,
this method with set previous page as currentPage and call bring to front function.
Example:
import { BrowserName, BrowserInstance, expect } from "playwright-elements";
async function useSwitchToPreviousTab() {
await BrowserInstance.start(BrowserName.WEBKIT);
await BrowserInstance.startNewPage();
await BrowserInstance.currentPage.goto(`https://playwright.dev`);
await BrowserInstance.startNewPage();
expect(BrowserInstance.currentPage).toHaveURL('about:blank');
await BrowserInstance.switchToPreviousTab();
expect(BrowserInstance.currentPage).toHaveURL('https://playwright.dev');
}
Switch tab by index
switchToTabByIndex(): Promise<void>
when new page is opened BrowserInstance
stores pointer on previous one,
this method with set page with specific index as currentPage and call bring to front function.
Example:
import { BrowserName, BrowserInstance, expect } from "playwright-elements";
async function useSwitchToTabByIndex() {
await BrowserInstance.start(BrowserName.WEBKIT);
await BrowserInstance.startNewPage();
await BrowserInstance.currentPage.goto(`https://playwright.dev`);
await BrowserInstance.startNewPage();
expect(BrowserInstance.currentPage).toHaveURL('about:blank');
await BrowserInstance.switchToTabByIndex(0);
expect(BrowserInstance.currentPage).toHaveURL('https://playwright.dev');
}