I have a component which uses the react-datepicker
package.
I am writing to write a unit test which will edits the dates and thereafter run some logic. However, i am unable to detect the field which for me to change using userEvent.type()
. I have tried to use getByText, getByRole, getAllByText.
Form.tsx
import React, { useState } from 'react';
import DatePicker from "react-datepicker";
import { Form } from 'react-bootstrap';
import "react-datepicker/dist/react-datepicker.css";
const Form = () => {
const [data, setData] = useState({ date1: new Date(), date2: new Date() })
return (
<div>
<Form>
...some other fields
<Form.Group controlId="date1">
<Form.Label>Date1</Form.Label>
<DatePicker name='date1'selected={data.date1} onChange={(date: Date) => setData({...data, date1: date})}
</Form.Group>
<Form.Group controlId="date2">
<Form.Label>Date2</Form.Label>
<DatePicker name='date2' selected={data.date2} onChange={(date: Date) => setData({...data, date2: date})}
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</div>
)
}
export default Form
Form.test.tsx
import React from 'react';
import Form from './Form';
import {render} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
describe('Form Component', () => {
it('able to change the date', () => {
const { getByRole } = render(<Form/>)
const date1Field = getByRole('textbox', { name: /date1/i })
act(() => userEvent.type(date1Field, '01/01/1990'))
... any other action to submit the form
})
})
However, my terminal showed me, which is the same for both date, which it was unable to detect the input field:
TestingLibraryElementError: Unable to find an accessible element with the role"textbox" and name "/date1/i"
textbox:
Name=""
<input
class=''
name='date1'
type='text'
value='05/23/2021'
/>
Name=""
<input
class=''
name='date2'
type='text'
value='05/23/2021'
/>
There is an issue with the library itself and not being able to pass in any ARIA props into the datepicker in react-datepicker
.
With using the other library you mentioned react-day-picker
it is possible to pass props into the input and set aria labels.
import DayPickerInput from 'react-day-picker/DayPickerInput';
<DayPickerInput inputProps={{'aria-label':'Date input 2'}} />
Sandbox: https://codesandbox.io/s/react-day-picker-examplesinput-forked-lj8pp