【问题标题】:How to write a Jasmine test for printer function如何为打印机功能编写 Jasmine 测试
【发布时间】:2020-11-28 18:29:47
【问题描述】:

我正在尝试为以下打印功能编写 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();
  }) );

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

【问题讨论】:

  • 您当前的测试有什么问题?

标签: javascript angular typescript jasmine


【解决方案1】:

您必须确保window.open() 返回一个功能齐全的对象,因为被测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(); 
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多