How to write a Jasmine test for printer function

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-11 12:36:43

问题


I am trying to write a Jasmine test for the following print function:

  printContent( contentName: string ) {
    this._console.Information( `${this.codeName}.printContent: ${contentName}`)
    let printContents = document.getElementById( contentName ).innerHTML;
    const windowPrint = window.open('', '', 'left=0,top=0,width=925,height=1400,toolbar=0,scrollbars=0,status=0');
    windowPrint.document.write(printContents);
    windowPrint.document.close();
    windowPrint.focus();
    windowPrint.print();
    windowPrint.close();
  }

I am more than willing to change the function to be more testable. This is my current test:

  it( 'printContent should open a window ...', fakeAsync( () => {
    spyOn( window, 'open' );
    sut.printContent( 'printContent' );
    expect( window.open ).toHaveBeenCalled();
  }) );

I am trying to get better code coverage.


回答1:


You must make sure, window.open() returns a fully featured object since the printContent method under test uses properties and functions of windowPrint. Such an object is typically created with createSpyObj.

var doc = jasmine.createSpyObj('document', ['write', 'close']);
var windowPrint = jasmine.createSpyObj('windowPrint', ['focus', 'print', 'close']);
windowPrint.document = doc; 
spyOn(window, 'open').and.returnValue(windowPrint);

Your amended unit test would then look as follows:

it( 'printContent should open a window ...', () => {

  // given
  var doc = jasmine.createSpyObj('document', ['write', 'close']);
  var windowPrint = jasmine.createSpyObj('windowPrint', ['focus', 'print', 'close']);
  windowPrint.document = doc;
  spyOn(window, 'open').and.returnValue(windowPrint);

  // when
  sut.printContent('printContent');

  // then
  expect(window.open).toHaveBeenCalledWith('', '', 'left=0,top=0,width=925,height=1400,toolbar=0,scrollbars=0,status=0');
  expect(doc.write).toHaveBeenCalled(); 
  expect(doc.close).toHaveBeenCalled(); 
  expect(windowPrint.focus).toHaveBeenCalled(); 
  expect(windowPrint.print).toHaveBeenCalled(); 
  expect(windowPrint.close).toHaveBeenCalled(); 
});


来源:https://stackoverflow.com/questions/63318388/how-to-write-a-jasmine-test-for-printer-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!