在 playwright 中将方法作为参数传递

问题描述 投票:0回答:1

我有一个函数可以检查定位器是否具有特定文本,我想使用first()和last()作为参数等:

export async function checkLocatorByText(page: Page,locatorName: string,locatorPosition:string, text: string) {
    await expect(page.locator(locatorName).last()).toContainText(text);
}

例如,我有一个参数 locatorPosition,我想使用它,而不是直接硬编码 .last() 方法。我想稍后使用 .last() 方法作为参数,但我无法在函数中使用它。 我真正想要的结果是这样的

export async function checkLocatorByText(page: Page,locatorName: string,locatorPosition:string, text: string) {
    await expect(page.locator(locatorName).locatorName).toContainText(text);
}

我怎样才能实现这个目标?

typescript function methods parameters playwright-typescript
1个回答
0
投票

执行类似操作,您可以传递

"first"
"last"
或要检查的定位器的索引:

  async checkLocatorByText(
    page: Page,
    locatorName: string,
    locatorPosition: "first" | "last" | number,
    text: string
  ) {
    if (locatorPosition === "first") {
      await expect(page.locator(locatorName).first()).toContainText(text);
    } else if (locatorPosition === "last") {
      await expect(page.locator(locatorName).last()).toContainText(text);
    } else {
      await expect(page.locator(locatorName).nth(locatorPosition)).toContainText(text);
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.