【问题标题】:how to pass screen.height & screen.width in vue test case | Jest Framework如何在 vue 测试用例中传递 screen.height 和 screen.width |笑话框架
【发布时间】:2020-06-03 16:02:56
【问题描述】:

我已经使用 screen.height & screen.width 进行 js 操作。我无法通过测试用例。 (代码覆盖率)。我正在使用 vue utils - Jest 框架。 下面我的js代码

const clientWidth = this.clientWidth ? this.clientWidth : screen.width;
const clientHeight = this.clientHeight ? this.clientHeight : screen.height;

低于我在测试用例中尝试过的内容

it('should set the height of window screen', () =>{
    Object.defineProperty(HTMLElement.prototype, 'screen', {         
    height: {
        value: 100,
    }
    configurable: true, 
}); 

如何为这个场景编写测试用例。

【问题讨论】:

  • 你测试什么代码?如果是 window.screen,那么在 window 上模拟它会更有意义。
  • @EstusFlask 它不是 window.screen
  • @EstusFlask 它不是全局屏幕。我已经更新了我的 js 代码。请仔细查看
  • @EstusFlask 其实我是 js 新手。我在控制台中尝试了 screen.height 。它显示了一些价值。当我尝试 window.screen.height 时,它也返回相同的值。
  • 我明白了。你试图在 HTMLElement 上模拟它让我很困惑。我会发布一个答案。

标签: unit-testing vue.js vuejs2 jestjs vue-test-utils


【解决方案1】:

在这种情况下,screenwindow.screen,它是window.Screen 的一个实例。在浏览器和 Jest 的简化 DOM 实现 (jsdom) 中,它由使用属性描述符实现的只读属性组成。

screen 属性可以用Object.definePropertywindow 对象上模拟,或者widthheight 可以分别在Screen.prototypescreen 上用Object.defineProperty 模拟。

使用 Jest spy 模拟属性允许在每次测试后自动清理,而无需恢复 afterEach 中的属性描述符,还可以减少手动使用 Object.defineProperty 导致的样板:

jest.spyOn(screen, 'height', 'get').mockReturnValue(100);
expect(screen.height).toBe(100);
// evaluate piece of code that uses `screen`

【讨论】:

  • 无法窥探 height 属性;它不是一个函数 -> 我收到这样的错误
  • 从这个错误我想你正在做jest.spyOn(screen, 'height')。它应该是jest.spyOn(screen, 'height', 'get')
  • 不,我试过这个const spy = jest.spyOn(screen, 'height', 'set'); screen.height = 150; expect(spy).toHaveBeenCalled(); expect(screen.height).toBe(150);
  • 监视set 的目的不是很好,应该会导致错误。 screen.height 是只读的。
  • 在我的测试用例中,我必须通过屏幕高度。那么解决方案是什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
  • 2020-12-15
  • 1970-01-01
  • 2012-10-18
  • 2020-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多