3

I am doing testing for the first time so I am pretty much sure that I am doing something wrong.

I was writing test case and my component does this internally.

const {width, height} = Dimensions.get('window')

For my test case, I was considering iPhone 11 which have dimensions as width: 414, height:896, and I want this consistent across all the test cases.

React native testing library while testing sets width as 750 and height as 1334.

I want to change it to iPhone 11 dimensions, I searched web and found articles which uses jest.mock to change function.

So I did something like this

it('renders correctly', () => {
     jest.mock("Dimensions", () => ({
        get: jest.fn().mockReturnValue({ width: 414, height:896 }),
     }))
      
     const {getByTestId} = render(<Home />)
 

Home component have console.log(width, height) but it is still giving width as 750 and height as 1334 (because of which my test case is failing).

How can I fix it?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Alwaysblue
  • 9,948
  • 38
  • 121
  • 210

3 Answers3

4

If you want to mock Dimensions.get return value on a per-test basis, you can create the following mock function with jest.doMock.

const mockDimensions = ({ width, height }) => {
    jest.resetModules()
    jest.doMock('react-native/Libraries/Utilities/Dimensions', () => ({
        get: jest.fn().mockReturnValue({ width, height })
    }))
}

Then call it at the beginning of your tests as follows.

it('renders correctly', () => {
    mockDimensions({ width: 414, height: 896 })  
    const { getByTestId } = render(<Home />)
    // Your assertions
})

jest.doMock is used instead of jest.mock to avoid hoisting, which allows us to mock the dimensions on each test rather than globally.

juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • This works for `ios` but for some reason it fails in a `web` environment, when making use of `react-native-web`, I'm using with `jest-expo` config – conor909 Jan 07 '22 at 12:17
1

This worked for me for ios

import { Dimensions } from 'react-native';

 jest.spyOn(Dimensions, 'get').mockReturnValue({ width: 414, height: 818 });
1

In the test, we override the screen width returned by Dimensions

  const Dimensions = jest.requireActual(
    "react-native/Libraries/Utilities/Dimensions"
  );

  return {
    ...Dimensions,
    get: (param) => {
      if (param === "window") {
        return {
          width: 310,
        };
      }
    },
  };
});