【问题标题】:How to skip window.location.reload in angular unittest如何在角度单元测试中跳过 window.location.reload
【发布时间】:2020-09-25 11:00:16
【问题描述】:
我正在为使用 window.location.reload() 的组件文件之一编写规范文件。
toggleFloatingFilter() {
this.hasFloatingFilter = !this.hasFloatingFilter;
this.clearSelectedRows();
this.gridApi.setRowData(this.rowData);
if (!this.hasFloatingFilter) {
this.gridApi.setFilterModel(null);
this.loadData();
}
setTimeout(() => {
this.gridApi.refreshHeader();
}, 0);
window.location.reload();
}
当我在 window.location.reload() 部分运行测试时,测试从头开始并重复。我可以知道如何在单元测试中跳过 window.location.reload
【问题讨论】:
标签:
javascript
angular
typescript
jasmine
karma-jasmine
【解决方案1】:
您需要以不同的方式使用window 对象来覆盖默认行为
在你component.ts
export class SomeComponent{
compWindow: any;
constructor(){
this.compWindow = window;
}
toggleFloatingFilter() {
this.hasFloatingFilter = !this.hasFloatingFilter;
this.clearSelectedRows();
this.gridApi.setRowData(this.rowData);
if (!this.hasFloatingFilter) {
this.gridApi.setFilterModel(null);
this.loadData();
}
setTimeout(() => {
this.gridApi.refreshHeader();
}, 0);
this.compWindow.location.reload(); // access like this
}
}
然后在spec文件中:
const myWindow = {
location: {
reload() { return 'something'; }
}
};
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [BrowserModule],
declarations: [SomeComponent],
providers:
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(SomeComponent);
component = fixture.componentInstance;
component.compWindow = myWindow; // this would override the value we are setting in constructor.
fixture.detectChanges(); // once we have overridden it, now call "detectChanges"
});
}));