使用 Cypress,如何测试尝试关闭选项卡会导致显示确认框?

问题描述 投票:0回答:1

我想测试关闭选项卡(或重新加载选项卡)是否会显示确认框。如果用户单击“取消”,确认框应该消失并且页面不会重新加载。

我尝试用这样的东西来测试:

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

但是,这失败了 - 页面只是重新加载并且确认框没有出现。 (确认框肯定有效)。

javascript dom-events cypress
1个回答
0
投票

这是我曾经使用过的另一种解决方法

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

我可能是一个很好的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.