单元测试:如何使用Angular + Jasmine模拟窗口对象的innerWidth属性?

时间:2019-06-14 10:33:22

标签: angular unit-testing testing jasmine angular8

我想编写一个单元测试,期望该变量根据窗口的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属性?

1 个答案:

答案 0 :(得分: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
}

}