如何为打印机功能编写Jasmine测试 [英] How to write a Jasmine test for printer function

查看:63
本文介绍了如何为打印机功能编写Jasmine测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为以下打印功能编写一个茉莉花测试:

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.

推荐答案

您必须确保,window.open()返回一个功能齐全的对象,因为被测试的printContent方法使用了windowPrint的属性和功能.通常使用 createSpyObj 创建此类对象.

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

这篇关于如何为打印机功能编写Jasmine测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆