1

I am writing a spec file for one of my component files in which the window.location.reload() is used.

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();
  }

When i run the test once it hits the window.location.reload() part the test starts from the beginning and it gets repeated. Can i know how-to skip the window.location.reload in unit test

Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
Nidhin Kumar
  • 3,278
  • 9
  • 40
  • 72
  • https://stackoverflow.com/questions/34177221/how-to-inject-window-into-a-service If you inject the window as a dependency into the component, you should be able to mock it easier by something like `spyOn(component.window.location, 'reload');`. Using `window` directly may give you a tough time if you ever do server side rendering. – AliF50 Sep 25 '20 at 12:49

1 Answers1

1

You need to use window object in a diff way to override the default behavior

In you 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
  }

}

and then in spec file:

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

Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104