如何为打印机功能编写 Jasmine 测试

How to write a Jasmine test for printer function

我正在尝试为以下打印函数编写 Jasmine 测试:

  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();
  }

我非常愿意将函数更改为更易于测试。这是我目前的测试:

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

我正在努力获得更好的代码覆盖率。

您必须确保,window.open() returns 是一个功能齐全的对象,因为被测试的 printContent 方法使用了 windowPrint 的属性和函数。这样的对象通常使用 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);

您修改后的单元测试将如下所示:

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(); 
});