如何开玩笑地从 mui 中模拟 x-date-pickers?

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

我在我的应用程序中添加了一个 DateTimePicker,它似乎可以工作,但是,我无法在我的 Jest 测试中模拟选择器。

我不断收到以下错误:

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)

我已经尝试了以下各项,但无法开玩笑地检测模拟。

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");

下面是抛出错误的行。这只是一个常规的导入语句:

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

我的模拟文件位于“../../../mocks/x-date-pickers”相对于单元测试文件的位置。我还没有期待模拟工作,但我至少期待它被拾起。

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);
        }}
    />
);

如有任何帮助,我们将不胜感激!

问题是我需要将 DateTimePicker 添加到模拟的末尾:

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