为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

梵蒂冈之花 2023-03-24 14:34:46
我正在为我的其中一个组件文件编写规范文件,其中使用了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
查看完整描述

1 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

您需要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"

      });

  }));


查看完整回答
反对 回复 2023-03-24
  • 1 回答
  • 0 关注
  • 66 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信