You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 21:45:34