Reputation: 2001
Edit: Non working repo with slightly different approach
I need to mock out the material UI date pickers for my tests (working under the assumption that they have their own tests so I shouldn't need to test that). I managed to get this up and running when having a mock inside my test file as per the below:
jest.mock('@material-ui/pickers', () => {
const actual = jest.requireActual('@material-ui/pickers');
return {
...actual,
DatePicker: (() => (props: any): JSX.Element => {
return (
<input
data-testid="mockedDateField"
onChange={(e): void => {
props.onChange(e.target.value);
}}
/>
);
})(),
};
});
However I want to move this to the __mocks__
folder such that I don't have to repeat the code block above in all my test suites. The __mocks__
folder is a sibling of node_modules
.
To this end, I created __mocks__\@material-ui\pickers\index.js
with the following block:
import React from 'react';
const actual = jest.requireActual('@material-ui/pickers');
const mockMaterialUiPickers = {
...actual,
DatePicker: () => (props) => {
return (
<input
data-testid="mockedDateField"
onChange={(e) => {
props.onChange(e.target.value);
}}
/>
);
},
};
export default mockMaterialUiPickers;
Unfortunately it doesn't seem like this is being picked up properly.
I have added jest.mock('@material-ui/pickers')
to my test
file.
This is then imported in my components using the following
import { DatePicker } from '@material-ui/pickers';
I am assuming that my problem is with the path of my mocks, however i am unable to figure out what the correct one is!
Thanks in advance.
Upvotes: 1
Views: 2000
Reputation: 391
In my case, creating src/__mocks__/@material-ui/pickers.tsx
file with the implementation below did the trick (I'm using TypeScript, but I assume JavaScript implementation would be similar):
import React from 'react';
import { DatePickerProps } from '@material-ui/pickers';
const actual = jest.requireActual('@material-ui/pickers');
export const MuiPickersUtilsProvider = actual.MuiPickersUtilsProvider;
export const DatePicker = (props: DatePickerProps) => (
<input
data-testid="mockedDateField"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
props.onChange(e.target.value);
}}
/>
);
Upvotes: 1
Reputation: 51
From what I read here, you have to name your mock file __mocks__\@material-ui\pickers.js
.
Upvotes: 1