Playwright|ロケーター

Playwright

ロケーターとはページ上の要素を見つける機能です。
Playwrightの主なロケーターメソッドはこちらです。

  1. page.getByRole()
  2. page.getByLabel()
  3. page.getByPlaceholder()
  4. page.get.Bytext()
  5. page.getByAltText()
  6. page.getByTitle
  7. page.getByTestid
  8. その他

1. getByRole()

HTMLのアクセシビリティ属性に基づいて要素を検索します。

例えば「ボタン」をクリックしたいテストを書きたいとき
HTMLがこのように書かれていたとします

<div>
  <button>ログイン</button>
</div>

このHTMLに対してロールを探したい場合以下のように書きます。

await expect(
  page.getByRole('button', { name: 'ログイン' })
).toBeVisible();

getByRole()で指定可能な、よく使うロール例はこちらです。

HTMLの該当タグPlsywrightのロール
ダイアログ<dialog>dialog
ボタン<button>button
チェックボックス<input type=”checkbox”>checkbox
テキストボックス<input>
<test area>
textbox
オプション<option>option
リンク
<a>,
<area>
link

2. getByLabel()

HTMLのラベルテキストに基づいて要素を検索します。

<label for="searchbox">検索</label>
<input id="searchbox" type="text"> 
await expect(
  page.getByLabel(/検索/)
).toBeVisible();

3. getByPlaceholder()

HTMLのプレースホルダー属性を持つ要素を検索します。

<input type="text" placeholder="入力してください">
await expect(
  page.getByPlaceholder(/入力してください/)
).toBeVisible();

4. get.Bytext()

要素に含まれるテキストを検索します。

<nav>
  <span>ホーム</span>
</nav>
await expect(
  page.getByText(/ホーム/)
).toBeVisible();

5. getByAltText()

HTMLのalt属性に基づいて画像等の要素を検索します。

<img src="cat.png" alt="ねこ">
await expect(
  page.getByAltText(/ねこ/)
).toBeVisible();

6. getByTitle

タイトル属性に基づいて要素を検索します。

<button title="これみて">詳細</button>
await expect(
  page.getByTitle(/これみて/)
).toBeVisible();

7. getByTestid

data-testid属性に基づいて要素を検索します。

<div data-testid="admin">管理者メニュー</div>
await expect(
  page.getByTestId('admin')
).toBeVisible();

8.その他

CSSセレクターやXPathを使ったロケーターもあります。
構造に依存したテストとなるため、あまり使わない方が望ましいです。

CSSのタグ指定

await expect(
  page.locator('button')
).toBeVisible();

id指定

<button id="login-btn">ログイン</button>
await expect(
  page.locator('#login-btn')
).toBeVisible();

CSSセレクターで指定

await expect(
  page.locator('div > button')
).toBeVisible();

XPathで指定

await expect(
  page.locator('//button[text()="ログイン"]')
).toBeVisible();

まとめ

ロケーターの選択で壊れにくいテストになります。
実装するうえでも下記の順で実装するのがおすすめです。

  1. getByRole()
  2. getByLabel()
  3. getByPlaceholder()
  4. getByText()
  5. getByAltText()
  6. getByTitle()
  7. getByTestId()
  8. CSS / XPath(最後の手段)

参考にしてみてください。

タイトルとURLをコピーしました