Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

feat(console api): first/last/nth (#19485)

Dmitry Gozman1263bc3edd40
diff --git a/packages/playwright-core/src/server/injected/consoleApi.ts b/packages/playwright-core/src/server/injected/consoleApi.ts
index 4059c64709..2ab0da8dd2 100644
--- a/packages/playwright-core/src/server/injected/consoleApi.ts
+++ b/packages/playwright-core/src/server/injected/consoleApi.ts
@@ -54,6 +54,9 @@ class Locator {
self.getByTitle = (text: string | RegExp, options?: { exact?: boolean }): Locator => self.locator(getByTitleSelector(text, options));
self.getByRole = (role: string, options: ByRoleOptions = {}): Locator => self.locator(getByRoleSelector(role, options));
self.filter = (options?: { hasText?: string | RegExp, has?: Locator }): Locator => new Locator(injectedScript, selector, options);
+ self.first = (): Locator => self.locator('nth=0');
+ self.last = (): Locator => self.locator('nth=-1');
+ self.nth = (index: number): Locator => self.locator(`nth=${index}`);
}
}
@@ -82,6 +85,9 @@ class ConsoleAPI {
...new Locator(injectedScript, ''),
};
delete window.playwright.filter;
+ delete window.playwright.first;
+ delete window.playwright.last;
+ delete window.playwright.nth;
}
private _querySelector(selector: string, strict: boolean): (Element | undefined) {
diff --git a/tests/library/inspector/console-api.spec.ts b/tests/library/inspector/console-api.spec.ts
index 8d1bde91a3..e7afa12e1b 100644
--- a/tests/library/inspector/console-api.spec.ts
+++ b/tests/library/inspector/console-api.spec.ts
@@ -72,4 +72,26 @@ it('should support playwright.getBy*', async ({ page }) => {
expect(await page.evaluate(`playwright.getByText('hello').element.innerHTML`)).toContain('Hello');
expect(await page.evaluate(`playwright.getByTitle('world').element.innerHTML`)).toContain('World');
expect(await page.evaluate(`playwright.locator('span').filter({ hasText: 'hello' }).element.innerHTML`)).toContain('Hello');
+ expect(await page.evaluate(`playwright.locator('span').first().element.innerHTML`)).toContain('Hello');
+ expect(await page.evaluate(`playwright.locator('span').last().element.innerHTML`)).toContain('World');
+ expect(await page.evaluate(`playwright.locator('span').nth(1).element.innerHTML`)).toContain('World');
+});
+
+it('expected properties on playwright object', async ({ page }) => {
+ expect(await page.evaluate(`Object.keys(playwright)`)).toEqual([
+ '$',
+ '$$',
+ 'inspect',
+ 'selector',
+ 'generateLocator',
+ 'resume',
+ 'locator',
+ 'getByTestId',
+ 'getByAltText',
+ 'getByLabel',
+ 'getByPlaceholder',
+ 'getByText',
+ 'getByTitle',
+ 'getByRole',
+ ]);
});