0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Playwrightでリンクをクリックしても画面遷移しなかった原因

0
Posted at

概要

Playwrightでリンクをクリックして画面遷移するE2Eテストを作成したところ、期待したURLへ遷移せずテストが失敗しました。

原因は、リンクではなくlistitemをクリックしていたことでした。

やりたいこと

Playwrightでリンクをクリックし、別の画面へ遷移することを確認したい。

実行したコード

test("リンクをクリックすると別の画面に遷移する", async ({ page }) => {
  const samplePage = new SamplePage(page);
  const destinationPage = new DestinationPage(page);

  await samplePage.goto();

  await samplePage.gotoDestination();

  await expect(page).toHaveURL("/sample");

  await expect(destinationPage.getPageTitle).toBeVisible();
});

Page Objectでは、以下のようにリンクを取得していました。

export class SamplePage extends BasePage {
  readonly getList: Locator;
  readonly getSampleLink: Locator;

  constructor(page: Page) {
    super(page);

    this.getList = page.getByRole("list");

    this.getSampleLink = this.getList.getByRole("listitem").filter({
      has: page.getByRole("link", { name: /サンプル/ }),
    });
  }

  async goto() {
    await this.page.goto("/");
  }

  async gotoDestination() {
    await this.getSampleLink.click();
  }
}

実行結果

テストが失敗しました。

エラー内容

期待していたURLへ遷移せず、元のURLのままでした。

Error: expect(page).toHaveURL(expected) failed

Expected: "http://localhost:5173/sample"
Received: "http://localhost:5173/"
Timeout: 5000ms

原因調査

ローカルで実際にリンクをクリックすると、正常に画面遷移しました。

また、Playwrightで以下のようにリンクを直接取得してクリックした場合も成功しました。

await page.getByRole("link", { name: /サンプル/ }).click();

Page Objectで定義していたLocatorを確認しました。

this.getSampleLink = this.getList.getByRole("listitem").filter({
  has: page.getByRole("link", { name: /サンプル/ }),
});

原因

リンクではなくlistitemをクリックしていたことが原因でした。

filter()は、指定した条件に一致する要素に絞り込むためのものです。

以下のコードでは、リンクを持つlistitemに絞り込んでいるだけなので、取得されるLocatorはlistitemのままでした。

this.getList.getByRole("listitem").filter({
  has: page.getByRole("link", { name: /サンプル/ }),
});

そのため、click()ではリンクではなくlistitemをクリックしていました。

解決策

listitemから、その中にあるリンクを取得するように変更しました。

this.getSampleLink = this.getList
  .getByRole("listitem")
  .getByRole("link", { name: /サンプル/ });

学んだこと

Playwrightのfilter()は子要素を取得するものではなく、現在のLocatorを条件によって絞り込むためのものだと分かりました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?