在react-native-web
/expo
设置中,在使用jest
with和config 进行测试期间jest-expo
,以下模拟似乎总是在 web 中,但在 ios 中。web
ios
0
300
考试:
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)
})
})
组件:
import { useWindowDimensions } from 'react-native'
export function useOrientation() {
const { width, height } = useWindowDimensions()
return {
width,
height,
isPortrait: height > width,
isLandscape: width > height
}
}