如何在角度单元测试中跳过 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()部分,测试就会从头开始并重复进行。我能知道如何在单元测试中跳过window.location.reload


梵蒂冈之花
浏览 99回答 1
1回答

明月笑刀无情

您需要window以不同的方式使用对象来覆盖默认行为在你的component.tsexport 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"      });  }));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript