💬
Playwrightでの要素特定の優先順位
以下の優先順位で要素特定をすれば良い
- VSCode拡張のPlaywright Test for VSCodeで利用できるPick locatorで取得する
- 1.で取得したものが動的に変わる(例えば、テスト実行やユーザーごとに変わる※1)のであれば、
data-testid
を利用する
※1 以下はPick locatorでは記事名で特定しようとしているが、テスト実行状況で変わってしまう
Pick locatorではどのような順番で要素の手段をしているのか
以下のロケータ順に探している(と思われる)
- page.getByRole() to locate by explicit and implicit accessibility attributes.
- page.getByText() to locate by text content.
- page.getByLabel() to locate a form control by associated label's text.
- page.getByPlaceholder() to locate an input by placeholder.
- page.getByAltText() to locate an element, usually image, by its text alternative.
- page.getByTitle() to locate an element by its title attribute.
- page.getByTestId() to locate an element based on its data-testid attribute (other attributes can be configured).
ユーザーが目にすることができる情報を利用して要素特定をしている。
しかし、data-testidのようなユーザーから見えない(例えば、ブラウザの開発者ツールを使わないと見えない)のは利用しないようにしている。
getByRole()
を一番優先度高く使うのであれば、開発者とWAI-ARIAがソースコードに記述されているのか?を会話も重要である。
これから考えたいこと
特に、SPAは動的にページが変わるので推奨されていない。
なので、次の手段で代替できないか?を考える
- Filtering Locatorsを利用して要素を特定する
- テストデータ(ユーザーから見えるデータ)を一意にして要素を特定できるようにする
Discussion