问题
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