1

我想编写一个单元测试,它期望一个变量包含一个取决于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属性吗?

4

1 回答 1

0

不要认为这是可能的。作为一种解决方法,我创建了另一个变量来存储 的值,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
}

}

于 2019-06-14T11:26:48.290 回答