问题
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) { // ... }
回答1:
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',
},
});
...
});
});
});
来源:https://stackoverflow.com/questions/51949523/mock-window-object-in-jasmine-angular