scy
scy

Reputation: 327

jasmine window.location.reload in ngOnDestroy

public ngOnDestroy(): void { window.location.reload(); }

How can I unit test this? All answers I found didn't work or only worked when the test was the only one executed. It looks like jasmine is inherently calling ngOnDestroy() outside of a test suite scope. Mocking ngOnDestroy() and writing a console.log into the real thing also always resulted in a console output.

specs:

For completion, I tried the following:

(also checked every possibility in beforeAll(), afterEach() and afterAll())

Upvotes: 1

Views: 1600

Answers (1)

satanTime
satanTime

Reputation: 13574

window is your dependency, therefore, it should be injected as any other dependency, for example, as a token:

export const WINDOW = new InjectionToken('WINDOW');

then, in the module of Component, you need to provide it:

@NgModule({
  // ...
  providers: [
    {
      provide: WINDOW,
      useValue: window,
    },
  ],
  // ...
})

then, inject it in your Component, you need to inject it as dependency:

export class Component {
  constructor(@Inject(WINDOW) private window: Window) {}

  public ngOnDestroy(): void {
    this.window.location.reload(); // add this.
  }
}

Now, you can mock it in your tests:

beforeEach(() => {
  return TestBed.configureTestingModule({
    declarations: [Component],
    providers: [
      {
        provide: WINDOW,
        useValue: {
          location: {
            reload: () => undefined, // or a spy
          },
        },
      },
    ],
  }).compileComponents();
});

Profit!

Upvotes: 3

Related Questions