LoginSignup
0
0

More than 1 year has passed since last update.

Cypressでホバー した際のCSSを確認する

Posted at

最近Cypressを使ってE2Eテストを行なっているのですが、Hoverした際にCSSの表示が適切に変わっているかテスト出来なかったため、方法を調査してみました。

■原因:

こちらの記事にて、下記内容がまとめられていました。

This comes closer to our real-world scenario, as our icon is shown when a mouseover event is fired. Note that this event is not the same thing as CSS :hover state. When you run this test, you can see that the board item does not change color. Since this is change is handled by CSS, there is no real way we can trigger this change using JavaScript.

Cypressのmouseoverイベント(下記参照)でHoverした際のJavaScriptの挙動はテストできるけれど、CSSのテストは出来ないよ!という事でした。

cy.get('.menu-item').trigger('mouseover')

■どうするか:

最初に載せた記事を参考に、ライブラリ cypress-real-events をインストールしました。

開発環境のみで使えればいいので、--devをつけてコマンドを叩き、インストールしています。

yarn add cypress-real-events --dev

■導入してみる:

下記の書き方をすればいいようです。

クリックした時:

cy.get("button").realClick();
cy.get("button").realClick(options);

ホバーした時:

cy.get("button").realHover();
cy.get("button").realHover(options);

Cypressに書いてみる

hogehoge.cy.ts
import 'cypress-real-events'

describe('コンポーネントのテスト', () => {
 it('Hoverした際にボタンが薄くなること', () => {
  //Hoverしていない時
  cy.get('button').should('have.css', 'opacity', '1')

  //Hoverしている時
  cy.get('button').realHover().should('have.css', 'opacity', '0.7')
 })
})

無事に通りました👏

■まとめ:

今回はCypressでHoverした際に、CSSが適切になっているかを確認する方法を調査しました。
Cypressに元々ある、mouseoverイベントではJSの判断しか出来ないため、ライブラリの使用が必要なようです。

閲覧ありがとうございました!

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