We will get this error because we are mocking ‘@mui/x-date-pickers/internals/demo’ as follows.
jest.mock('@mui/x-date-pickers/internals/demo', () => {
DemoContainer: jest.fn((props) => {
return null;
})
})
but here it is not covering components={[‘DatePicker’, ‘TimePicker’]} in the <DemoContainer components={[‘DatePicker’, ‘TimePicker’]}> as we are returning null in the mock. So it is throwing the error as Cannot read properties of undefined (reading ‘DemoContainer’). So here we need to mock DatePicker and TimePicker as follows.
import { render } from '@testing-library/react';
import * as React from 'react';
import App from './index';
const DatePickerMock = () => <div>Mocked DatePicker</div>;
const TimePickerMock = () => <div>Mocked TimePicker</div>
jest.mock('@mui/x-date-pickers/internals/demo', () => ({
DemoContainer: jest.fn(({ components }) => (
<div>
{components.includes('DatePicker') && <DatePickerMock />}
{components.includes('TimePicker') && <TimePickerMock />}
</div>
)),
}))
const renderApp = () => {
return render(
<App />
);
};
describe('App Component', () => {
it('renders without crashing', () => {
const { asFragment } = renderApp();
expect(asFragment()).toMatchSnapshot();
});
});