import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Input } from '../Input';
describe('Input', () => {
it('renders input field correctly', () => {
render();
expect(screen.getByPlaceholderText('Enter text')).toBeInTheDocument();
});
it('renders label when provided', () => {
render();
expect(screen.getByText('Email')).toBeInTheDocument();
});
it('renders error message when error prop is provided', () => {
render();
expect(screen.getByText('This field is required')).toBeInTheDocument();
});
it('renders helper text when provided and no error', () => {
render();
expect(screen.getByText('Enter your email address')).toBeInTheDocument();
});
it('does not render helper text when error is present', () => {
render(
);
expect(screen.queryByText('This should not be visible')).not.toBeInTheDocument();
});
it('applies error styling when error prop is provided', () => {
render();
const input = screen.getByRole('textbox');
expect(input).toHaveClass('border-error');
});
it('applies full width when specified', () => {
render();
const input = screen.getByRole('textbox');
expect(input).toHaveClass('w-full');
});
it('disables input when disabled prop is true', () => {
render();
const input = screen.getByRole('textbox');
expect(input).toBeDisabled();
});
it('accepts user input', async () => {
const user = userEvent.setup();
render();
const input = screen.getByPlaceholderText('Type here') as HTMLInputElement;
await user.type(input, 'Hello World');
expect(input.value).toBe('Hello World');
});
it('calls onChange when value changes', async () => {
const user = userEvent.setup();
const handleChange = jest.fn();
render();
const input = screen.getByRole('textbox');
await user.type(input, 'test');
expect(handleChange).toHaveBeenCalled();
});
it('applies custom className', () => {
render();
const input = screen.getByRole('textbox');
expect(input).toHaveClass('custom-input');
});
it('sets aria-invalid when error is present', () => {
render();
const input = screen.getByRole('textbox');
expect(input).toHaveAttribute('aria-invalid', 'true');
});
it('sets aria-describedby correctly for error', () => {
render();
const input = screen.getByRole('textbox');
expect(input).toHaveAttribute('aria-describedby', 'test-input-error');
});
it('forwards ref correctly', () => {
const ref = React.createRef();
render();
expect(ref.current).toBeInstanceOf(HTMLInputElement);
});
});