如何在角度单位测试中跳过window.location.reload



我正在为我的一个组件文件编写一个规范文件,其中使用了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((部分,测试就会从头开始,并重复进行。我能知道如何在单元测试中跳过窗口.location.reload

您需要以不同的方式使用window对象来覆盖默认行为

组件中。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"
});
}));

最新更新