Skip to content

Instantly share code, notes, and snippets.

@jeffwhelpley
Last active July 13, 2018 11:48
Show Gist options
  • Save jeffwhelpley/2d14a615790af18b3549 to your computer and use it in GitHub Desktop.
Save jeffwhelpley/2d14a615790af18b3549 to your computer and use it in GitHub Desktop.
Using window object in Angular 2
// interface for Window
interface Window {
// add some stuff here
}
let someMockWindowObject = {
// add some mock functionality here
};
// for browser providers
provide(Window, { useValue: window });
// for node and testing
provide(Window, { useValue: someMockWindowObject })
// inject it
class Foo {
constructor(private window: Window) {}
}
@akilanrbt
Copy link

Does this hold true for the latest angular 2 beta as well?

Copy link

ghost commented Sep 3, 2016

Anyway you could provide a plunker showing how to use it in a component?

@Abhinav8101988
Copy link

Please provide the actual test case. Because i tried using this but was unable to create the mock object using Window interface. Also it is not allowing to create a Window interface by own because it already finds it in the typings.

I have a line of code in the component which states
window.location.href="any url";
As it gives the full page load test case fails.

There are many properties in the actual Window interface so it is not possible to create the mock for it.

@jerradpatch
Copy link

here is an angular4 example, thanks for the code @jeffwhelpley

app.module.ts

providers:[
        {provide: Window, useValue: window }
    ],

x.component.ts

      constructor(private window: Window) {
        this.setVal = window.innerHeight ;
    }

@whyboris
Copy link

whyboris commented Jul 13, 2018

For reference and unit testing, here is what worked for me:
In my service (can be done in a component too):

  setUpBeforeunload(): void {
    window.addEventListener('beforeunload', this.closeConnection);
  }

In my spec (Jasmine testing):

    it('should set up window eventListener', () => {
      spyOn(window, 'addEventListener');
      service.setUpBeforeunload();
      expect(window.addEventListener).toHaveBeenCalledWith('beforeunload', service.closeConnection);
    });

And another test:

    it('should call closeConnection()', () => {
      spyOn(service, 'closeConnection');
      service.setUpBeforeunload();
      window.dispatchEvent(new Event('beforeunload'));
      expect(service.closeConnection).toHaveBeenCalled();
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment