'Jest mock dimensions not changing

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?



Solution 1:[1]

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.

Solution 2:[2]

This worked for me for ios

import { Dimensions } from 'react-native';

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Trevor Lane