import React from 'react'; import { screen, within, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { composeStories } from '@storybook/testing-react'; import * as stories from './TextField.stories'; import { renderWithTheme } from '@lendi-ui/test-utils'; const { ClearAction, ClearActionWithValue } = composeStories(stories); const getElements = () => { return { Uncontrolled: screen.getByLabelText('Uncontrolled with clear action') as HTMLInputElement, Controlled: screen.getByLabelText('Controlled with clear action') as HTMLInputElement, }; }; describe('Text field - Clear action', () => { it('should clear the input value when clear button is clicked - Uncontrolled', async () => { renderWithTheme(); const { Uncontrolled } = getElements(); userEvent.type(Uncontrolled, 'some text'); expect(Uncontrolled.value).toBe('some text'); const UncontrolledBtn = within(screen.getByTestId('uncontrolled')).getByLabelText('Clear'); userEvent.click(UncontrolledBtn); await waitFor(() => { expect(screen.getByLabelText('Uncontrolled with clear action')).toHaveValue(''); }); }); it('should clear the input value when clear button is clicked - Controlled', () => { renderWithTheme(); const { Controlled } = getElements(); userEvent.type(Controlled, 'some text'); expect(Controlled.value).toBe('some text'); const ControlledBtn = within(screen.getByTestId('controlled')).getByLabelText('Clear'); userEvent.click(ControlledBtn); expect(Controlled.value).toBe(''); }); it('should not display the clear button when the input is cleared', () => { renderWithTheme(); const { Controlled } = getElements(); const ControlledBtn = () => within(screen.getByTestId('controlled')).queryByLabelText('Clear'); userEvent.type(Controlled, 'some text'); expect(ControlledBtn()).not.toBeNull(); userEvent.clear(Controlled); expect(ControlledBtn()).toBeNull(); }); it('should display clear button when a value is provided on render', () => { renderWithTheme(); const ControlledBtn = () => within(screen.getByTestId('controlled-value')).queryByLabelText('Clear'); expect(ControlledBtn()).not.toBeNull(); const UncontrolledBtn = () => within(screen.getByTestId('uncontrolled-value')).queryByLabelText('Clear'); expect(UncontrolledBtn()).not.toBeNull(); }); });