【问题标题】:Unit testing: How do I mock the innerWidth property on the window object with Angular + Jasmine?单元测试:如何使用 Angular + Jasmine 模拟窗口对象的 innerWidth 属性?
【发布时间】:2019-06-14 10:33:22
【问题描述】:

我想编写一个单元测试,它期望一个变量包含一个特定值,具体取决于窗口的innerWidth

在我的单元测试中,我使用window.innerWidth = 1000;。但是,我收到一条错误消息,上面写着Cannot assign to 'innerWidth' because it is a read-only property.

代码(home.component.spec.ts):

  xit('should order the cards in the appropriate order on desktop', () => {
    spyOn(component, 'reOrderCards');
    window.innerWidth = 1000;
  })

有没有办法模拟innerWidth 属性?

【问题讨论】:

    标签: angular unit-testing testing jasmine angular8


    【解决方案1】:

    不要认为这是可能的。作为一种解决方法,我创建了另一个变量来存储innerWidth 的值,以便对其进行正确的单元测试。

    public screenWidth: number;
    
    ngOnInit() {
       this.screenWidth = window.innerWidth; // Get initial innerWidth so the variable is immediately defined for reOrderCards() to recognise
       this.reOrderCards();
    }
    
    
      @HostListener('window:resize', [])
      onResize() {
        this.screenWidth = window.innerWidth;
        this.reOrderCards();
      }
    
    reOrderCards() {
    if(this.screenWidth < 768) {
     // Do logic
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2021-03-31
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 2016-08-02
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多