点击某个链接或按钮,在新页面 (设为新 tab) 打开了某个地址
将这个测试用例分成两个:第一个,监听 window.open 函数是否被调用过 (如果是其他方式,可以采用同样的道理);第二个,直接通过cy.visit
访问这个 url,然后检查或做后续的步骤...
思路参考源自此stackoverflow 链接
Accessing new windows via Cypress is not possible in its current version.
However, there are many ways this functionality can be tested in Cypress now. You can split up your tests into separate pieces and still have confidence that your application is covered.
- Write a test to check that when performing the action in your app, the window.open event is called by using cy.spy() to listen for a window.open event.
- In a new test, use cy.visit() to go to the url that would have opened in the new window, fill in the fields and click the buttons like you would in a Cypress test.
cy.visit('http://localhost:3000', {
onBeforeLoad(win) {
cy.stub(win, 'open')
})
}
// Do the action in your app like cy.get('.open-window-btn').click()
cy.window().its('open').should('be.called')
cy.visit('http://localhost:3000/new-window')
// Do the actions you want to test in the new window
Fullly working test example can be found here.
Cypress 入门系列:
注:目前官方团队正在开发 Python 版本,同样的 Free to use,对 JS 恐惧的同学不妨等一等,或者直接 JS 上手,非常简单,VSCode 装上之后,你会爱上 Cypress 和 JS,笔者会慢慢介绍各种 Web UI 自动化复杂场景下 Cypress 的强大应对,目前还没发现 Cypress 无法处理的问题!欢迎一起入坑!QQ 群:947886065.