skip to Main Content

I want to test that closing a tab (or reloading the tab) results in a confirmation box being displayed. If the user clicks ‘cancel’, the confirmation box should disappear and the page didn’t reload.

I tried to test this with something like this:

cy.on('window:confirm', () => false)
cy.reload()

However, this fails – the page just reloads & the confirmation box doesn’t appear. (The confirmation box is definitely working).

2

Answers


  1. Here is another work around, that I ever used

    describe('Tab close confirmation', () => {
       it('should display confirmation box when attempting to close tab', () => {
         cy.visit('your_page_url'); // Replace 'your_page_url' with the URL of the page you want to test
    
         cy.on('window:before:unload', (e) => {
         const confirmationMessage = 'Are you sure you want to leave?';
         e.returnValue = confirmationMessage; // For modern browsers
         return confirmationMessage; // For older browsers
       });
    
       cy.get('body').type('{cmd}w'); // Close the tab (You can use '{ctrl}w' for Windows)
    
       cy.on('window:confirm', (text) => {
       expect(text).to.equal('Are you sure you want to leave?');
       return true; // Simulate user confirming the close
       });
      });
    });
    

    I may be a good solution for you.

    Login or Signup to reply.
  2. Try stubbing the window:confirm and verifying the stub has been called:

    cy.window().then((win) =>
      cy.stub(win, 'confirm').as('confirm').returns(false)
    )
    
    cy.reload()
    
    cy.get('@confirm').should('have.been.calledOnce')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search