Jest & React Testing Library: How to Access Element for getAllByText()
I Try to Write a Unit Test for a Date Picker Component of My Application. I Don't Know How to Access to Start Day and End Day Elements Inside getAllByText()...
I try to write a unit test for a date picker component of my application. I don't know how to access to start day and end day elements inside getAllByText() for DateRangePicker.
Here is the date picker component
export const DatePicker = (props) => (
<Stack direction="row" spacing="2">
<Field
name={props.datePickerName + 'Day'}
label={<Trans id="whenDidItStart.startDay" />}
component={TextInput}
//group={props.group}
w={70}
maxLength="2"
/>
<Field
name={props.datePickerName + 'Month'}
label={<Trans id="whenDidItStart.startMonth" />}
component={TextInput}
//group={props.group}
w={70}
maxLength="2"
/>
<Field
name={props.datePickerName + 'Year'}
label={<Trans id="whenDidItStart.startYear" />}
component={TextInput}
//group={props.group}
w={110}
maxLength="4"
/>
</Stack>
)
export const SingleDatePicker = (props) => {
return (
<Stack spacing={4} pb="5">
<Field
name={props.name}
datePickerName={props.datePickerName}
group={props.group}
label={props.label}
helperText={props.helperText}
component={DatePicker}
/>
</Stack>
)
}
export const DateRangePicker = (props) => {
return (
<React.Fragment>
<SingleDatePicker
name={props.name + 'Start'}
datePickerName="start"
group={props.group}
label={props.startLabel}
helperText={props.helperText}
/>
<SingleDatePicker
name={props.name + 'End'}
datePickerName="end"
group={props.group}
label={props.endLabel}
helperText={props.helperText}
/>
</React.Fragment>
)
}
Here is the unit test
describe('<DatePicker />', () => {
afterEach(cleanup)
it('properly renders DatePicker components', () => {
const submitMock = jest.fn()
const { getAllByText, getByRole } = render(
<I18nProvider i18n={i18n}>
<ThemeProvider theme={canada}>
<Form
initialValues=""
onSubmit={submitMock}
render={() => <DatePicker datePickerName="test" />}
/>
</ThemeProvider>
</I18nProvider>,
)
screen.debug()
const testDay = getAllByText(/)
expect(testDay).toHaveLength(1)
const testMonth = getAllByText(/)
expect(testMonth).toHaveLength(1)
const testYear = getAllByText(/)
expect(testYear).toHaveLength(1)
})
it('properly renders DateRangePicker components', () => {
const submitMock = jest.fn()
const { getAllByText, getByRole } = render(
<I18nProvider i18n={i18n}>
<ThemeProvider theme={canada}>
<Form
initialValues=""
onSubmit={submitMock}
render={() => <DateRangePicker label="dateRangePickerTest" name="dateRangePickerTest" />}
/>
</ThemeProvider>
</I18nProvider>,
)
const testStartDate = getAllByText(/***start day****/)
expect(testStartDate).toHaveLength(1)
const testEndDate = getAllByText(/***end day***/)
expect(testEndDate).toHaveLength(1)
})
})
I have tried getAllByText(/) and
getAllByText(/)
but jest gives error: >Unable to find an element with the text: /.