I have a component in my AngularJS application that is functioning correctly. However, when it comes to test coverage, everything after the 'window.addEventListener('message',' part is not being covered.
Should I create a mock object for the 'window' and provide my own implementation for 'addEventListener', or should I spy on it and verify that it has been called?
Here is the code for my.component.controller.ts:
export class MyComponentController {
constructor() {}
public theEventOccurred(e: any) {
let json = JSON.parse(e.data);
console.log(json.document);
}
public $onInit() {
window.addEventListener('message', (event) => {
this.theEventOccurred(event);
}, false);
}
}
And here is the testing file code in my.component.spec.ts:
describe('Component: my', () => {
let $componentController: angular.IComponentControllerService;
let scope: angular.IScope;
beforeEach(inject(
($rootScope: angular.IScope,
_$componentController_: angular.IComponentControllerService) => {
scope = $rootScope.$new();
$componentController = _$componentController_;
}));
describe('Controller: MyComponentController', () => {
it('should log json.document', () => {
let ctrl: any = $componentController('my', { $scope: scope });
ctrl.$onInit();
});
});
});