[英]Unit testing: How do I mock the innerWidth property on the window object with Angular + Jasmine?
我想編寫一個單元測試,它期望一個變量包含一個特定的值,具體取決於窗口的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
屬性?
不要認為這是可能的。 作為一種解決方法,我創建了另一個變量來存儲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
}
}
您可以嘗試從另一個方法返回 window.innerwidth 並模擬該函數以根據需要返回不同的值。
https://emailtoanees.medium.com/angular-unit-test-window-innerwidth-c523d2e64eaf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.