mercredi 24 juin 2020

Jest - Mock React Native Hook useWindowDimension

Problem

I have a function I want to unit test that contains the React Native hook useWindowDimensions so I want to mock this hook. The function is in it's own file and called within a React Native functional component. I would like to mock this hook so I can easily unit test my function and I'm running into errors.

Error

"Invalid hook call. Hooks can only be called inside the body of a react component"

Does anyone have a suggestion as to how to mock this hook using Jest?

Function

export function windowDimensions(): WindowDimensions {
         const windowWidth = Math.round(useWindowDimensions().width);   // I want to mock useWindowDimensions here
         const windowHeight = Math.round(useWindowDimensions().height); // I want to mock useWindowDimensions here
         const minWindowDimension = Math.min(windowWidth, windowHeight);
         const maxWindowDimension = Math.max(windowWidth, windowHeight);
         return { minWindowDimension, maxWindowDimension };
       }

Test file

import {windowDimensions} from '../dimensions';
    describe('windowDimensions return value', () => {
     beforeEach(() => {
          jest.mock("react-native", () => ({
            useWindowDimensions: () => ({
              width: 375,
              height: 812
            })
          }));
     });
        it('should return windowWidth', () => {
        expect(windowDimensions()).toEqual({minWindowDimenion: 375, maxWindowDimension: 812});
      });

    }); 

Aucun commentaire:

Enregistrer un commentaire