如何在 angular 单元测试中跳过 window.location.reload

How to skip window.location.reload in angular unittest

我正在为我的其中一个组件文件编写规范文件,其中使用了 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

您需要以不同的方式使用 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"
      });
  }));