LoginSignup
0
0

toHaveAttributeで要素の属性をチェックする

Last updated at Posted at 2023-10-16

フロントエンドのテストにおいて要素の属性をチェックする必要があり、jest-domtoHaveAttributeについて調べたので簡単に記録しておきます。

jest-domとは?

jest-domは、jestのカスタムマッチャー(アサーションメソッド)を提供するライブラリです。DOM要素に対するテストをより宣言的に、読みやすく、そして保守しやすくできるようです。

toHaveAttributeとは?

指定したDOM要素が特定の属性と値を持っているかどうかを確認できるメソッドです。

実装例

同じテキストを持つが、異なるページに遷移するケースです。

<a href="https://example1.com">詳しくはこちら</a>
<a href="https://example2.com">詳しくはこちら</a>
<a href="https://example3.com">詳しくはこちら</a>
const links = await findAllByText("詳しくはこちら");

expect(links[0]).toHaveAttribute("href", "https://example1.com");

これによって、指定したhref属性に正しいURLが値として渡されているかを確認することができます。

エラーメッセージの例

ケースによってエラーメッセージがどのように変わるか気になったので試してみました。

  • その要素自体がundefinedだった場合
expect(undefined).toHaveAttribute("href", "https://example1.com")

expect(received).toHaveAttribute()

received value must be an HTMLElement or an SVGElement.
Received has value: undefined
  • その要素が指定した属性を持たない場合
expect(element).toHaveAttribute("type", "submit") // element.getAttribute("type") === "submit"

Expected the element to have attribute:
  type="submit"
Received:
  null
  • その要素が指定した値を持たない場合
expect(element).toHaveAttribute("href", "https://example.com") // element.getAttribute("href") === "https://example.com"

Expected the element to have attribute:
  href="https://example.com"
Received:
  href="https://example1.com"
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