React Testing Library: Unable to Change Material UI DatePicker Input Value

I’m trying to change the value of the Material UI Datepicker Input with React Testing Library. But it doesn’t seem to work with fireEvent.change().

import React from "react";
import { render, screen, waitFor, fireEvent } from "@testing-library/react";

import MomentUtils from "@date-io/moment";
import { DatePicker, MuiPickersUtilsProvider } from "@material-ui/pickers";

describe("DatePicker", () => {
    test("Change datepicker value", async () => {
        render(
            <MuiPickersUtilsProvider utils={MomentUtils}>
                <DatePicker
                    label="Start Date"
                    id="startDate"
                    onChange={(date) => {
                        return undefined;
                    }}
                    value={new Date()}
                    format={"yyyy/MM/DD"}
                />
            </MuiPickersUtilsProvider>
        );

        const startDateInput = (await screen.findByLabelText("Start Date")) as HTMLInputElement;
        screen.debug(startDateInput);
        fireEvent.change(startDateInput, { target: { value: "2021/01/01" } });
        expect(startDateInput.value).toBe("2021/01/01");
    });

Here is what jest reports:

console.log
    <input
      aria-invalid="false"
      class="MuiInputBase-input MuiInput-input"
      id="startDate"
      readonly=""
      type="text"
      value="2021/08/01"
    />

expect(received).toBe(expected) // Object.is equality

    Expected: "2021/01/01"
    Received: "2021/08/27"

Any suggestions are appreciated 🙂

Answer

DatePicker by default will open the calendar view and will not allow you to provide keyboard inputs . You need to use the KeyboardDatePicker instead .

import React, { useState } from "react";
import { render, screen, fireEvent } from "@testing-library/react";

import DateFnsUtils from "@date-io/date-fns";
import {
  KeyboardDatePicker,
  MuiPickersUtilsProvider,
} from "@material-ui/pickers";

const DatePickerExample = () => {
  const [date, setDate] = useState(new Date());

  return (
    <MuiPickersUtilsProvider utils={DateFnsUtils}>
      <KeyboardDatePicker
        clearable
        label="Start Date"
        id="startDate"
        onChange={(date) => {
          setDate(date);
        }}
        value={date}
        format={"yyyy/MM/dd"}
      />
    </MuiPickersUtilsProvider>
  );
};

describe("DatePicker", () => {
  test("Change datepicker value", () => {
    render(<DatePickerExample />);

    const startDateInput = screen.getByLabelText("Start Date");
    fireEvent.change(startDateInput, { target: { value: "2021/01/01" } });
    expect(startDateInput.value).toBe("2021/01/01");
  });
});