As @estus mentioned in the comment, you'd be better getting the hash from the Router. But to answer your question directly, you need to inject window into the place you're using it, so that during testing you can mock it.
First, register window with the angular2 provider - probably somewhere global if you use this all over the place:
import { provide } from '@angular/core';
provide(Window, { useValue: window });
This tells angular when the dependency injection asks for the type Window
, it should return the global window
.
Now, in the place you're using it, you inject this into your class instead of using the global directly:
import { Component } from '@angular/core';
@Component({ ... })
export default class MyCoolComponent {
constructor (
window: Window
) {}
public myCoolFunction () {
let hash: string;
hash = this.window.location.hash;
}
}
Now you're ready to mock that value in your test.
import {
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
injectAsync
} from 'angular2/testing';
let myMockWindow: Window;
beforeEachProviders(() => [
//Probably mock your thing a bit better than this..
myMockWindow = <any> { location: <any> { hash: 'WAOW-MOCK-HASH' }};
provide(Window, {useValue: myMockWindow})
]);
it('should do the things', () => {
let mockHash = myMockWindow.location.hash;
//...
});