I have a resuable component, called DatePicker like this
export interface IPDatePicker extends IProps {
control: any
label: string
placeholder: string
value?: string
errorText?: string
isRequired?: boolean
name: string
defaultValue?: any
onChangeText: (value: string) => void
minimumDate?: any
maximumDate?: any
timeOnly?: boolean
hideLabel?: boolean
labelMaxLine?: number
// setDateValue: any
}
const DatePicker: React.FC<IPDatePicker> = props => {
const todaysDate = new Date()
const [date, setDate] = useState<Date>(todaysDate)
const [isDatePickerOpen, setIsDatePickerOpen] = useState(false)
return (
<Controller
name={props?.name}
defaultValue={props?.defaultValue}
control={props?.control}
render={({field: {onChange, value}}: any) => {.....}
/>
The point is, the component needs 'control' as mandatory parameters.
The 'control' is from the parent page/component using useForm
const ParentPage = () => {
const {
control,
formState: {errors, isValid, isDirty},
} = useForm({
resolver,
mode: 'onChange',
defaultValues: {
date: '',
},
})
}
return (
...
<DatePicker
control={control} <-here
name='date'
...
/>
)
I tried to create a test file but I cant figure it out how to call useForm on jest. It always show Invalid hook call. Hooks can only be called inside of the body of a function component
import React from 'react'
import {render, fireEvent} from '@testing-library/react-native'
import {IProps} from '@app/presentations/types'
import {DatePicker} from '@app/presentations/_shared-components'
import {useForm} from 'react-hook-form'
interface IPDatePicker extends IProps {
control: any
label: string
placeholder: string
value?: string
errorText?: string
isRequired?: boolean
name: string
defaultValue?: any
onChangeText: (value: string) => void
}
function renderComponent(props: IPDatePicker) {
const component = render(<DatePicker {...props} />)
return {
component,
...component,
}
}
describe('DatePicker component', () => {
it('Should render correctly', () => {
const {control} = useForm({
mode: 'onChange',
defaultValues: {
date: '',
},
})
const component = renderComponent({
control: control,
label: 'Date picker',
placeholder: 'Placeholder',
onChangeText: v => {},
name: 'date',
})
expect(component).toMatchSnapshot()
})
})
my question is similar to this