Search code examples
reactjsdatepickerantdreact-testing-library

Reset date value in antd datepicker(react-testing-library)


I want to test the functionality of clicking on the clear icon that appears on hovering on the antd datepicker but it's not working for me.

it('should clear start date', async () => {
        render(<Component />)
        const startDate = screen.getByPlaceholderText('SEARCH_START_DATE_PLACEHOLDER')
        // startDate.focus()
        fireEvent.mouseOver(startDate)
        const closeIcon = screen.getAllByRole('img', { name: 'close-circle' })[0]
        await act(async () => {
            await fireEvent.click(closeIcon)
        })
        console.log(startDate.getAttribute('value'), 'value')
        const endDate = screen.getByPlaceholderText("SEARCH_END_DATE_PLACEHOLDER");
        await fireEvent.mouseDown(endDate);
        await fireEvent.change(endDate, { target: { value: "2022-05-03" } });
        await act(async () => {
            fireEvent.click(document.querySelectorAll(".ant-picker-cell-selected")[0]);
        })
    })

Any help would be appreciated.

Solution

  • First, You should select the container of the icon, not the icon itself.

    Change:

    const closeIcon = screen.getAllByRole('img', { name: 'close-circle' })[0]
    

    To:

    const closeIcon = (screen.getAllByRole('img', { name: 'close-circle' })[0]).parentElement
    

    Then, use mouseUp event instead of click event.

    Change:

    await fireEvent.click(closeIcon)
    

    To:

    await fireEvent.mouseUp(closeIcon)