其他测试框架 强大的全新 Web UI 测试框架 Cypress - Cypress 处理新页签

非洲赵子龙 for Cypress · 2019年03月04日 · 最后由 wzhNavy 回复于 2023年04月25日 · 4132 次阅读
  • 场景

点击某个链接或按钮,在新页面 (设为新 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.

  1. 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.
  2. 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.

共收到 6 条回复 时间 点赞

官方给了好几个新 tab 的解决方案,目前我用的这个,特别好用

不过在这个方案不完全适用于所有场景,在某些前端技术方案实现中,还是需要去 stub 后续事件

嗯,应该是这个目前没有唯一万能的处理办法,只能 “对症下药” 了。可以把几种方法积累起来,形成解决方案储备栈,针对具体的场景去尝试, 最稳定和最快的,作为最优选!

大大,有没有什么办法可以验证 A 域名跳转到 B 域名后的 url。测试过程中即使跳转到 B,断言也依然在 A 域名下去做匹配。

业务是这样的,A 站点击商品会在新标签页打开 B 站商品详情,URL 会带上相关的参数,该如何验证跳转后的 URL 是否包含对应参数呢,官方文档指出 visit 无法在同一个测试中打开不同域名,针对这种跳转形式的没有说明。
(以前相同的业务需求采用的 phantomJS+selenium 去做校验的。)

请教大佬个问题,点击一个按钮,跳转到一个新开的面签页面,cypress 脚本代码没有跳转到新页面,所以找不到元素报错,后续的代码都执行不了了,大佬有什么方案可以解决吗?已经被这个问题卡很久了😭

目前用的第二种方案解决这个问题

大佬们,用 top.window.location.href 下载文件的该如何处理

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册