How to mock x-date-pickers from mui in jest?

Issue

I added a DateTimePicker to my app which seems to work, however, I’m unable to mock the picker in my Jest tests.

I keep getting the following error:

Test suite failed to run

    TypeError: (0 , _material.generateUtilityClasses) is not a function

       7 | import type { Property, EnumProperty } from "../../types";
    >  8 | import { DateTimePicker } from "@mui/x-date-pickers/DateTimePicker";
         | ^
       9 | import { DateTime } from "luxon";

 at Object.<anonymous> (node_modules/@mui/x-date-pickers/node/internals/components/PickersToolbarText.js:32:54)
      at Object.<anonymous> (node_modules/@mui/x-date-pickers/node/DateTimePicker/DateTimePickerToolbar.js:20:27)
      at Object.<anonymous> (node_modules/@mui/x-date-pickers/node/DesktopDateTimePicker/DesktopDateTimePicker.js:20:30)
      at Object.<anonymous> (node_modules/@mui/x-date-pickers/node/DesktopDateTimePicker/index.js:13:30)
      at Object.<anonymous> (node_modules/@mui/x-date-pickers/node/DateTimePicker/DateTimePicker.js:22:30)
      at Object.<anonymous> (node_modules/@mui/x-date-pickers/node/DateTimePicker/index.js:13:23)
      at Object.<anonymous> (src/components/myFile/myFile.tsx:8:1)

I’ve tried each of the following, but can’t get jest to detect the mock.

jest.mock("@mui/x-date-pickers", () => require("../../../__mocks__/x-date-pickers"));
jest.mock("@mui/x-date-pickers", () => (
    <div>
        Hello
    </div>
));
jest.mock("@mui/x-date-pickers");

Below is the line throwing the error. It’s just a regular import statement:

import { DateTimePicker } from "@mui/x-date-pickers/DateTimePicker";

My mocked file at the location "../../../mocks/x-date-pickers" relative to the unit test file. I’m not expecting the mock to work yet, but I’m at least expecting it to be picked up.

import React from "react";
import { DateTimePickerProps } from "@mui/x-date-pickers";

export const DateTimePicker = (props: DateTimePickerProps) => (
    <input
        data-testid="mockedDateField"
        onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
            props.onChange(event.target.value);
        }}
    />
);

Any help would be appreciated!

Solution

The problem was I needed to add DateTimePicker to the end of my mock:

jest.mock("@mui/x-date-pickers/DateTimePicker", () => require("../../../__mocks__/x-date-pickers"));

Answered By – avenmia

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.