【问题标题】: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

【问题讨论】:

  • stackoverflow.com/questions/34177221/… 如果您将窗口作为依赖项注入到组件中,您应该能够通过类似spyOn(component.window.location, 'reload'); 的方式更轻松地模拟它。如果您曾经进行服务器端渲染,直接使用window 可能会给您带来困难。

标签: 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"
      });
  }));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2013-07-05
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多