【发布时间】:2022-07-27 17:57:46
【问题描述】:
如何处理 Cypress 中的窗口?
我面临的问题是,当我单击一个按钮时,会在一个新选项卡中打开一个新的浏览器窗口,其中包含要测试的实际页面。
我已经尝试了一切 -> window.open 和 window.location.replace 没有成功(目标 _blank 是不可能的,因为按钮中没有那个标签)
如何处理该功能?
提前致谢。
【问题讨论】:
标签: cypress
如何处理 Cypress 中的窗口?
我面临的问题是,当我单击一个按钮时,会在一个新选项卡中打开一个新的浏览器窗口,其中包含要测试的实际页面。
我已经尝试了一切 -> window.open 和 window.location.replace 没有成功(目标 _blank 是不可能的,因为按钮中没有那个标签)
如何处理该功能?
提前致谢。
【问题讨论】:
标签: cypress
问题是window.open 不能以通常(简单)的方式存根,这是一种防止浏览器劫持的安全功能。
这篇文章Stub window.open有另一种选择
TLDR - 在访问浏览器之前修改窗口
// ✅ CORRECT SOLUTION
it('opens a new window', () => {
// create a single stub we will use
const stub = cy.stub().as('open')
cy.on('window:before:load', (win) => {
cy.stub(win, 'open').callsFake(stub)
})
cy.visit('/')
// triggers the application to call window.open
cy.get('button').click('Open new window')
cy.get('@open').should('have.been.calledOnce')
【讨论】:
我发现了许多不同的方法来存根 window.open 调用,但没有一个是开箱即用的。
在我的用例中,有一个按钮可以启动点击事件。然后单击事件会打开一个新选项卡,其中包含我想要抓取的动态 url。
答案是一个很棒的帖子的组合:https://glebbahmutov.com/blog/stub-window-open/ 和 Cypress: Stub open window。
此示例应适用于 Cypress 10.x
// Listen to window:before:load events, modify the window object before the app code runs between page transitions
// Create a stub with the alias windowOpen, choose whatever you like
// Grab the url parameter that the page was trying to open and visit the page
cy.on('window:before:load', (win) => {
cy.stub(win, 'open').as('windowOpen').callsFake(url => {
cy.visit(url);
})
})
// Start by visiting the page you'll run your tests in. I'm using the baseUrl here.
cy.visit("/");
// Do whatever tests need to be done before the action the opens a new tab
// Now the element that fires a click event which then uses window.open to open a new tab
cy.contains("Ok").click();
// The stub should now have picked the url and called cy.visit(url)
// The page that would normally open in a new tab, should be visible in the same page
// Now the next commands are intended to run in the new page and should be able to complete
cy.get(".whateverselectoryouwant")
.should('have.text', 'whateveryourtextisonthenewpage')
【讨论】: