LoginSignup
4
1

はじめに

初めまして!
エンジニアになって数年、今まで本を読むだけでしたが、もっとプライベートで楽しみながら成長したい!自分が学んだ足跡を残していきたい!と思い記事を書きました!
最終的には自在に開発できるようになりたいと思っています。:triumph:
いろいろな記事を参考にさせてもらっています。:bow_tone2:

「いいね」か「ブックマーク」
を頂けると僕のモチベーションアップになります!:thumbsup:
少しでも気に入っていただけたらよろしくお願いいたします!:thumbsup:

今回の目的

storybookでUIテストをしたかった中でhoverのようなイベントでスタイルが適用されているか?を確認したかったため

バージョン

React:18
storybook: 8.1.10

ボタンの作りについて

storybookのサンプルを使用しています!
CSSのhoverは使用していません。
onMouseOverとonMouseLeaveでHoverの挙動を監視しstateに結果を格納します。

...
const [ isHover, setIsHover ] = useState(false)

<button
  type="button"
  className={['storybook-button', `storybook-button--${size}`, mode, isHover && 'storybook-button-hover'].join(' ')}
  data-testid='button'
  onMouseOver={()=>{setState(true)}}
  onMouseLeave={()=>{setState(false)}}
  {...props}
>
  {label}
  <style jsx>{`
    button {
      background-color: ${backgroundColor};
    }
  `}</style>
</button>

テストはこちら

storiesファイルはこちらです。
userEvent.hoverでhover状態に変更し、toHaveClassで適用されているか確認しましょう。

export const Primary: Story = {
  args: {
    primary: true,
    label: 'Button',
  },
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    // hover時のテスト
    await userEvent.hover(canvas.getByTestId('button'));
    await expect(canvas.getByTestId('button')).toHaveClass('storybook-button-hover');
    // unhover時のテスト
    await userEvent.unhover(canvas.getByTestId('button'));
    await expect(canvas.getByTestId('button')).not.toHaveClass('storybook-button-hover');
  },
};

結果はこちら

スクリーンショット 2024-06-22 17.20.46.png

参考

expect

userEvent

最後に

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

4
1
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
4
1