I have a function which I want to unit-test and into it I am comparing global objects window
& parent
as const isEqual = (window === parent)
;
Which is the best way how to mock those objects in Angular/TypeScript?
One more idea is to get those objects through function parameters, but anyway it's not solving this problem because I need to mock global window
object too if I am using getSomeData(win: Window, parent: Window) { // ... }
I went with this solution:
Create service which will inject window
object.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class GlobalObjectService {
public getWindow(): Window {
return window;
}
}
And in tests it's looks like:
describe('TestService', () => {
...
let globalObjectService: jasmine.SpyObj<GlobalObjectService>;
beforeEach(() => {
globalObjectService = jasmine.createSpyObj('GlobalObjectService', ['getWindow']);
...
});
describe('#testFunc', () => {
it('should test something', () => {
globalObjectService.getWindow.and.returnValue({
location: {
href: 'window.location.href',
},
});
...
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With