💬

Playwrightでの要素特定の優先順位

2025/01/03に公開

以下の優先順位で要素特定をすれば良い

  1. VSCode拡張のPlaywright Test for VSCodeで利用できるPick locatorで取得する
  2. 1.で取得したものが動的に変わる(例えば、テスト実行やユーザーごとに変わる※1)のであれば、data-testidを利用する

※1 以下はPick locatorでは記事名で特定しようとしているが、テスト実行状況で変わってしまう

Pick locatorではどのような順番で要素の手段をしているのか

以下のロケータ順に探している(と思われる)

  1. page.getByRole() to locate by explicit and implicit accessibility attributes.
  2. page.getByText() to locate by text content.
  3. page.getByLabel() to locate a form control by associated label's text.
  4. page.getByPlaceholder() to locate an input by placeholder.
  5. page.getByAltText() to locate an element, usually image, by its text alternative.
  6. page.getByTitle() to locate an element by its title attribute.
  7. page.getByTestId() to locate an element based on its data-testid attribute (other attributes can be configured).

ユーザーが目にすることができる情報を利用して要素特定をしている。
しかし、data-testidのようなユーザーから見えない(例えば、ブラウザの開発者ツールを使わないと見えない)のは利用しないようにしている。

getByRole() を一番優先度高く使うのであれば、開発者とWAI-ARIAがソースコードに記述されているのか?を会話も重要である。

これから考えたいこと

https://playwright.dev/docs/locators#locate-by-test-id
上記の通りPlaywrightは、data-testidを埋め込むことを推奨していない。
特に、SPAは動的にページが変わるので推奨されていない。

なので、次の手段で代替できないか?を考える

  • Filtering Locatorsを利用して要素を特定する
  • テストデータ(ユーザーから見えるデータ)を一意にして要素を特定できるようにする

Discussion