Reputation: 11961
How can I close a print window
open during on click of a print button in cypress. I am calling a js
function to close the window and its not performing the close, could someone please advise on how to resolve the problem ?
context('Print button tests', () => {
it.only('Verify the display of Print and close the window', () => {
cy.get('.timetable-filter-panel-button.btn.btn-primary > span')
.contains("Print current view")
.click();
printClose();
})
})
//Javascript function to close the open window:
function printClose(){
window.close();
}
Upvotes: 1
Views: 5506
Reputation: 1147
Here is a working example by using stub. Works in cypress v10.
What it does is call the stubbed window.print()
function, instead of opening the real dialogue and then trying to close it.
Because you just want to test if the print button will call window.print()
. This test should be enough.
Also, this will work across browsers and OSs.
describe('Test print', () => {
beforeEach(() => {
cy.visit('https://www.abc.net.au/news/2022-07-14/canada-raises-rates-1-percentage-point-could-australia-follow/101239294', {
onBeforeLoad(win) {
// Stub window.print functions here
cy.stub(win, 'print')
},
})
})
it('click print button should call the print dialog', () => {
cy.get('button._1KwgR._22AuU').click()
cy.get('button._1KwgR.vGCs_._2-5J1').click()
cy.window().its('print').should('be.called')
})
})
Upvotes: 1
Reputation: 6312
You test the print popup with Cypress like so:
it('Print button renders & opens modal', () => {
// Clicks & asserts the button that triggers the popup window to print
cy.get('[data-test="button-print"]')
.should('exist')
.and('be.visible')
.click();
// Assert printing was called once
cy.visit('/inner.html', {
onBeforeLoad: win => {
cy.stub(win, 'print');
},
});
cy.window().then(win => {
win.print();
expect(win.print).to.be.calledOnce;
// this line closes the print popup
cy.document().type({ esc });
});
});
Upvotes: -1