はじめに
初めまして!
エンジニアになって数年、今まで本を読むだけでしたが、もっとプライベートで楽しみながら成長したい!自分が学んだ足跡を残していきたい!と思い記事を書きました!
最終的には自在に開発できるようになりたいと思っています。
いろいろな記事を参考にさせてもらっています。
「いいね」か「ブックマーク」
を頂けると僕のモチベーションアップになります!
少しでも気に入っていただけたらよろしくお願いいたします!
今回の目的
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');
},
};
結果はこちら
参考
expect
userEvent
最後に
閲覧いただきありがとうございました!