You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Playwright for TypeScript中实例化空Locator

解决Playwright自定义嵌套TestId选择器问题

你不需要实例化“空Locator”,而是从页面根元素作为初始定位器,再链式调用getByTestId即可。另外注意代码里的语法错误:foreach应改为for...of。

基础实现方案

import { Page, Locator } from '@playwright/test';

export class CustomPage {
   protected readonly page: Page;
   
   constructor(page: Page) {
      this.page = page;
   }

   public getNestedElement(testIds: Array<string>): Locator {
      // 以页面根元素作为初始定位器
      let locator: Locator = this.page.locator(':root');

      for (const id of testIds) {
         locator = locator.getByTestId(id);
      }

      return locator;
   }
}

优化实现方案(更高效)

如果想避免空循环,或从第一个TestId直接开始链式查找,可以用以下写法:

import { Page, Locator } from '@playwright/test';

export class CustomPage {
   protected readonly page: Page;
   
   constructor(page: Page) {
      this.page = page;
   }

   public getNestedElement(testIds: Array<string>): Locator {
      if (testIds.length === 0) {
         return this.page.locator(':root');
      }

      // 从第一个TestId初始化,再链式处理剩余ID
      let locator = this.page.getByTestId(testIds[0]);
      for (const id of testIds.slice(1)) {
         locator = locator.getByTestId(id);
      }

      return locator;
   }
}

说明

  • :root是CSS伪类,指向文档根元素(HTML标签),作为初始定位器可以覆盖整个页面范围,后续getByTestId会在当前定位器的子元素中查找。
  • 两种写法都能实现嵌套查找:比如传入['parent-container', 'child-modal', 'grandchild-button'],最终会生成page.getByTestId('parent-container').getByTestId('child-modal').getByTestId('grandchild-button')的定位器,完全符合你的需求。

内容的提问来源于stack exchange,提问作者Lee McCready

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 13:52:20