如何用Jest与Testing-Library/React测试屏幕方向?Mock问题求助
解决Next.js中Jest测试window.screen.orientation.type的问题
问题原因
测试环境中window.screen.orientation默认是undefined,直接尝试spyOn会触发Cannot read properties of undefined或Cannot spyOn on a primitive value错误。
解决方案
方法一:直接定义mock对象
通过Object.defineProperty给window.screen.orientation赋值包含type属性的对象:
beforeEach(() => { Object.defineProperty(window.screen, 'orientation', { value: { type: 'portrait-primary' }, writable: true // 允许后续修改值 }); });
方法二:用jest.spyOn mock getter
因为orientation是window.screen的getter属性,需要mock它的getter返回包含type的对象:
beforeEach(() => { jest.spyOn(window.screen, 'orientation', 'get').mockReturnValue({ type: 'portrait-primary' }); });
完整测试示例
假设组件根据屏幕方向渲染不同内容:
import { render, screen } from '@testing-library/react'; import OrientationComponent from '../components/OrientationComponent'; describe('OrientationComponent', () => { beforeEach(() => { jest.spyOn(window.screen, 'orientation', 'get').mockReturnValue({ type: 'portrait-primary' }); }); afterEach(() => { jest.restoreAllMocks(); // 清除mock,避免影响其他测试 }); it('渲染竖屏提示文本', () => { render(<OrientationComponent />); expect(screen.getByText('当前为竖屏模式')).toBeInTheDocument(); }); it('渲染横屏提示文本', () => { // 覆盖mock的方向值 jest.spyOn(window.screen, 'orientation', 'get').mockReturnValue({ type: 'landscape-primary' }); render(<OrientationComponent />); expect(screen.getByText('当前为横屏模式')).toBeInTheDocument(); }); });
注意事项
- 测试完成后用
jest.restoreAllMocks()清除mock,防止测试用例间互相干扰 - 如果需要模拟
orientationchange事件,可以额外mockwindow.screen.orientation.addEventListener方法
内容的提问来源于stack exchange,提问作者Nazanin Roozbahani
相关产品推荐
相关产品推荐

