Had anyone tried mocking window.print?
I have a scenario where I need to click on a button that window.print's something, in order to move to the next step, and the test remains stuck in the browser print dialog box at the moment.
I tried with
cy.visit(url, { onBeforeLoad: win => cy.stub(win, 'print').returns(undefined) })
also with
cy.window(win => cy.stub(win, 'print').returns(undefined))
but each time I click on the printing button, I'm prompted with the browser print preview box.
Thank you!
Stubbing print definitely works. Put a debugger in your app code right before its about to call window.print and make sure its the stub as opposed to the native function.
As long as its stubbed it will not call through to the native function.
You're either stubbing the function too late (so after your app calls it), or you're doing something like transitioning to another page which then loses the stub.
You can use this event to always stub it on every page transition: https://docs.cypress.io/api/events/catalog-of-events.html#Window-Before-Load
it('can stub print', function () {
cy.visit('/inner.html', {
onBeforeLoad: (win) => {
cy.stub(win, 'print')
}
})
cy.window().then((win) => {
win.print()
expect(win.print).to.be.calledOnce
})
})

Closing this as this is a question, not a bug.
confirmed, sorry for the noise J
No problem. For the record you can stub anything so long as it is set to { configurable: true } when you do this:
Object.getOwnPropertyDescriptor(obj, 'prop')
If its set to false you cannot stub it - and the best practice in that case is to wrap that API in your own function and just stub that function.
For instance you cannot stub window.location API's.
So in that case
const myObj = {}
myObj.href = function (url) {
window.location.href = url
}
// in cypress code
cy.stub(myObj, 'href')
Most helpful comment