I\'m building some unit tests for a service in Angular2.
Within my Service I have the following code:
var hash: string;
hash = this.window.location.h
I really don't get why nobody provided the easiest solution which is the recommended way by the Angular-Team to test a service as you can see here. You even don't have to deal with the TestBed stuff at all in most of the cases.
Futhermore, you can use this approach for components and directives as well. In that case, you won't create a component-instance but a class-instance. This means, you don't have to deal with the child-components used within the components template as well.
Assuming you are able to inject Window into your constructor
constructor(@Inject(WINDOW_TOKEN) private _window: Window) {}
Just do the following in your .spec file:
describe('YourService', () => {
let service: YourService;
beforeEach(() => {
service = new YourService(
{
location: {hash: 'YourHash'} as any,
...
} as any,
...
);
});
}
I don't care about other properties, therefore I usually add a type cast to any. Feel free to include all other properties as well and type appropriately.
In case you need different values on the mocked properties you can simply spy on them and change the value using returnValue of jasmine:
const spy: any = spyOn((service as any)._window, 'location').and.returnValue({hash: 'AnotherHash'});
or
const spy: any = spyOn((service as any)._window.location, 'hash').and.returnValue('AnotherHash');