|
| 1 | +import type { Meta, StoryObj } from '@storybook/nextjs-vite'; |
| 2 | +import { useState } from 'react'; |
| 3 | +import { expect, screen, userEvent, waitFor } from 'storybook/test'; |
| 4 | +import CheckboxGroupField from '~/lib/form/components/fields/CheckboxGroup'; |
| 5 | + |
| 6 | +function ControlledCheckboxGroup() { |
| 7 | + const [values, setValues] = useState<(string | number)[]>(['a', 'b', 'c']); |
| 8 | + |
| 9 | + return ( |
| 10 | + <div> |
| 11 | + <CheckboxGroupField |
| 12 | + id="test" |
| 13 | + name="test" |
| 14 | + options={[ |
| 15 | + { value: 'a', label: 'Option A' }, |
| 16 | + { value: 'b', label: 'Option B' }, |
| 17 | + { value: 'c', label: 'Option C' }, |
| 18 | + ]} |
| 19 | + value={values} |
| 20 | + onChange={setValues} |
| 21 | + /> |
| 22 | + <div data-testid="result">{JSON.stringify(values)}</div> |
| 23 | + </div> |
| 24 | + ); |
| 25 | +} |
| 26 | + |
| 27 | +const meta: Meta = { |
| 28 | + title: 'Form/Fields/CheckboxGroup Interaction', |
| 29 | + component: ControlledCheckboxGroup, |
| 30 | +}; |
| 31 | + |
| 32 | +export default meta; |
| 33 | +type Story = StoryObj; |
| 34 | + |
| 35 | +export const ClickCheckbox: Story = { |
| 36 | + play: async () => { |
| 37 | + // Find checkbox C and verify it starts checked |
| 38 | + const checkboxC = await screen.findByRole('checkbox', { name: 'Option C' }); |
| 39 | + await expect(checkboxC).toHaveAttribute('aria-checked', 'true'); |
| 40 | + |
| 41 | + // Click to uncheck |
| 42 | + await userEvent.click(checkboxC); |
| 43 | + |
| 44 | + // Verify it unchecked |
| 45 | + await waitFor(async () => { |
| 46 | + await expect(checkboxC).toHaveAttribute('aria-checked', 'false'); |
| 47 | + }); |
| 48 | + |
| 49 | + await waitFor(async () => { |
| 50 | + await expect(screen.getByTestId('result')).toHaveTextContent('["a","b"]'); |
| 51 | + }); |
| 52 | + }, |
| 53 | +}; |
| 54 | + |
| 55 | +export const ClickLabel: Story = { |
| 56 | + play: async () => { |
| 57 | + // Find the text label and click it instead of the checkbox button |
| 58 | + const labelText = await screen.findByText('Option C'); |
| 59 | + await expect( |
| 60 | + screen.getByRole('checkbox', { name: 'Option C' }), |
| 61 | + ).toHaveAttribute('aria-checked', 'true'); |
| 62 | + |
| 63 | + await userEvent.click(labelText); |
| 64 | + |
| 65 | + await waitFor(async () => { |
| 66 | + await expect( |
| 67 | + screen.getByRole('checkbox', { name: 'Option C' }), |
| 68 | + ).toHaveAttribute('aria-checked', 'false'); |
| 69 | + }); |
| 70 | + |
| 71 | + await waitFor(async () => { |
| 72 | + await expect(screen.getByTestId('result')).toHaveTextContent('["a","b"]'); |
| 73 | + }); |
| 74 | + }, |
| 75 | +}; |
0 commit comments