1

In a react-native-web/expo setup, during tests using jest with jest-expo, web and ios config, the following mock always seems to be 0 in web yet 300 in ios.

The test:

import { renderHook } from '@testing-library/react-hooks'
import { useOrientation } from './index'

function mockDimensions({ width, height }) {
  jest.resetModules()
  jest.doMock('react-native/Libraries/Utilities/useWindowDimensions', () => {
    return {
      default: jest.fn(() => ({ width, height }))
    }
  })
}

describe('Test orientation outcome based on screen dimensions', () => {
  afterEach(cleanup)
  test('isPortrait should be true', async () => {
    mockDimensions({ width: 300, height: 600 })
    const { result: { current } } = renderHook(useOrientation)
    console.log(current.width). // <-- 0 in web, 300 in ios
    await expect(current.isPortrait).toBe(true)
    await expect(current.isLandscape).toBe(false)
  })
})

The component:

import { useWindowDimensions } from 'react-native'

export function useOrientation() {
  const { width, height } = useWindowDimensions()
  return {
    width,
    height,
    isPortrait: height > width,
    isLandscape: width > height
  }
}
conor909
  • 1,475
  • 14
  • 29

0 Answers0