1

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.

  • did you try spying on the document through the window object? ie - `spyOn(window.document, 'open')` etc? – nipuna-g Oct 03 '18 at 07:14
  • Yes. I have tried . It gave me same error 'TypeError: Cannot read property 'document' of undefined TypeError: Cannot read property 'document' of undefined ' – Narayana Bojja Oct 03 '18 at 08:48
  • I re-asked the question and got a working answer see: https://stackoverflow.com/questions/63318388/how-to-write-a-jasmine-test-for-printer-function – Phil Huhn Aug 09 '20 at 14:37

0 Answers0