import React from 'react';
import { render } from '@testing-library/react-native';
import { View } from 'react-native';
import FormItem from '../Item';
import Switch from '../../Switch';
import Input from '../../Input';
import { useForm } from 'react-hook-form';
// Mock Field component to verify ref is passed correctly
jest.mock('../../Field', () => {
const React = require('react');
const { View } = require('react-native');
const MockField = React.forwardRef((props: any, ref: any) => {
return (
{props.children}
);
});
MockField.displayName = 'MockField';
return MockField;
});
describe('FormItem ref handling', () => {
const TestForm = ({ children }: { children: React.ReactNode }) => {
const { control } = useForm({
defaultValues: {
testField: false,
inputField: '',
},
});
return (
{React.cloneElement(children as React.ReactElement, { control })}
);
};
it('should pass field.ref to Field component, not to child component', () => {
const TestComponent = () => (
);
const { getByTestId } = render();
// Field component should exist (mocked)
expect(getByTestId('mock-field')).toBeTruthy();
// Switch component should exist
expect(getByTestId('test-switch')).toBeTruthy();
});
it('should work with Input component', () => {
const TestComponent = () => (
);
const { getByTestId } = render();
// Field component should exist (mocked)
expect(getByTestId('mock-field')).toBeTruthy();
// Input component should exist
expect(getByTestId('test-input')).toBeTruthy();
});
it('should handle ref properly when used with useController', () => {
const TestComponent = () => {
const { control } = useForm({
defaultValues: {
testField: false,
},
});
return (
);
};
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
const { getByTestId } = render();
// Should render without warnings
expect(getByTestId('mock-field')).toBeTruthy();
expect(getByTestId('controller-switch')).toBeTruthy();
// Verify no ref-related warnings
const refWarnings = consoleSpy.mock.calls.filter(
(call) =>
call[0]?.includes('Function components cannot be given refs') ||
call[0]?.includes('forwardRef')
);
expect(refWarnings).toHaveLength(0);
consoleSpy.mockRestore();
});
it('should handle validation errors and ref focusing', () => {
const TestComponent = () => {
const { control } = useForm({
defaultValues: {
requiredField: '',
},
});
return (
);
};
const { getByTestId } = render();
// Field should receive the ref for error focusing
const fieldElement = getByTestId('mock-field');
expect(fieldElement).toBeTruthy();
// Input should be rendered normally without ref
expect(getByTestId('required-input')).toBeTruthy();
});
});