乐闻世界logo
搜索文章和话题

Cypress how to close the new window and back to main test window

1个答案

1

In Cypress, it natively supports operating and testing Single-Page Applications (SPA) within the same window. However, Cypress does not support directly opening new browser windows or tabs, nor does it support switching between different windows. This is because Cypress was designed from the start to avoid the complexity of multiple windows, maintaining simplicity and control in testing.

However, if your application opens new windows during testing, there is a way to handle this indirectly using Cypress:

  1. Intercepting Window Open Behavior: Since Cypress can intercept and control browser behavior, we can modify the window.open function to change the default behavior of opening new windows. Typically, when the page attempts to open a new window, we can redirect it to a new URL within the same window.

For example, if a button click opens a new window, we can write the following in the test script:

javascript
cy.window().then((win) => { cy.stub(win, 'open').callsFake((url) => { win.location.href = url; }); });

This code intercepts any attempt to open a new window via window.open and modifies the current window's location.href to the URL that the new window should open.

  1. Testing the Newly Opened Page: Once the new window's URL is redirected to the current window, Cypress can continue testing the elements and behavior of the new page within the same window.

  2. Returning to the Main Test Window: To return to the main page, you can simply use Cypress's navigation commands:

javascript
cy.go('back'); // Returns to the previous page, similar to the browser's back button

Or, if you know the URL of the main page, you can directly set it:

javascript
cy.visit('main page URL');

By doing this, Cypress can maintain testing within a single window environment while indirectly handling multi-window scenarios. The benefit is maintaining consistency and control in testing, avoiding the complexity and uncertainty introduced by multiple windows.

2024年6月29日 12:07 回复

你的答案