I have searched solution for this scenario. I found nothing. So, I am posting as a new question. I have a method in component which prints data in document like (control+P).
printContents;
popupWin;
print(): void {
this.printContents = document.getElementById('print-section2').innerHTML;
this.popupWin = window.open('', '_blank', 'top=500,left=500,height=100%,width=auto');
this.popupWin.document.open();
this.popupWin.document.write(`
<html>
<head>
<title>Zone 24x7 - Resource Allocation System
</title>
</br>
</br>
<style>table,tr,td{
border-collapse:collapse;
border:0.5px solid #000000;
}</style>
<style>h3{justify-content:center}
td{
width: 40%
}
</style>
</head>
<body onload="window.print();window.close()">${this.printContents}</body>
</html>`
);
this.popupWin.print();
this.popupWin.document.close();
}
I have tried to write below testcase for that one.
it('Print method should called', () => {
let viewEditResourceService = fixture.debugElement.injector.get(ViewEditResourceService);
spyOn(viewEditResourceService, 'getResourcebyId').and.returnValue(Observable.of(allocationModalCompObj.resDetails.data));
component.message = 298;
spyOn(window, 'open');
spyOn(document, 'open');
spyOn(document, 'write');
spyOn(window, 'print');
component.ngOnInit();
component.print();
expect(window.open).toHaveBeenCalled();
expect(window.print).toHaveBeenCalled();
});
It is giving below error
TypeError: Cannot read property 'document' of undefined TypeError: Cannot read property 'document' of undefined
I understood that This error because of spying window object. Any help is highly appreciated.