jeudi 14 mai 2020

Mocking @material-ui/pickers in Jest

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.

__mocks__ folder structure

Node modules structure for @materials-ui

Aucun commentaire:

Enregistrer un commentaire