Cypress web自动化37-cy.wrap() 操作 iframe 上的元素

前言

iframe 是一种常见的 web 页面上遇到的场景,像有些网站的登录就是放到 iframe 里面的。
cypress 如何处理 iframe 上的元素呢,cypress 目前没有提供类似 selenium 上的 switch_to.frame 这种直接切换的方法,得自己封装一个操作方法。

iframe场景

打开 https://www.126.com/ 首页,登录的输入框就是嵌套在iframe里面

/**
* Created by dell on 2020/6/9.
* 作者:上海-悠悠 交流QQ群:939110556
*/

describe('iframe login',function(){

// 定义getIframeBody方法
const getIframeBody = () => {
// 尝试获取 iframe > document > body
// 直到 body element 不为空
return cy
.get('iframe')
.its('0.contentDocument.body').should('not.be.empty')
// 包装body DOM元素以允许链接更多Cypress 命令, 如 ".find(...)"
// warp命令使用文档地址 https://on.cypress.io/wrap
.then(cy.wrap)
}

before( function() {
cy.visit("https://www.126.com/")
})

it("iframe type", function() {
// 定位输入框,输入账号
getIframeBody().find('[name="email"]').type("123@qq.com")
// 输入密码
getIframeBody().find('[name="password"]').type("123456")
// 点登陆按钮
getIframeBody().find('#dologin').click()

})
})

运行结果

注意:iframe 上的操作无法使用快照功能哦

自定义命令

我们可能会在多个测试用例访问iframe的元素,因此在 cypress 自定义命令 cypress/support/index.js 的文件里面添加一个命令。
自定义命令将自动在所有用例文件中使用,因为支持文件与每个用例文件串联在一起。

// cypress/support/index.js

/**
* Created by dell on 2020/6/9.
* 作者:上海-悠悠 交流QQ群:939110556
*/

Cypress.Commands.add('getIframeBody', () => {
// 定义getIframeBody方法
// and retry until the body element is not empty
return cy
.get('iframe')
.its('0.contentDocument.body').should('not.be.empty')
// 包装body DOM元素以允许链接更多Cypress 命令, 如 ".find(...)"
// warp命令使用文档地址 https://on.cypress.io/wrap
.then(cy.wrap)
})

用例文件内容 cypress/integration/iframe_login.js

// cypress/integration/iframe_login.js

/**
* Created by dell on 2020/6/9.
* 作者:上海-悠悠 交流QQ群:939110556
*/

describe('iframe login 126mail',function(){

before( function() {
cy.visit("https://www.126.com/")
})

it("login mail", function() {
// 定位输入框,输入账号
cy.getIframeBody()
.find('[name="email"]').type("123@qq.com")
.should('have.value', '123@qq.com')
// 输入密码
cy.getIframeBody()
.find('[name="password"]').type("123456")
.should('have.value', '123456')
// 点登陆按钮
cy.getIframeBody()
.find('#dologin').click()

})
})

运行结果

禁用log

我们可以通过禁用内部命令的日志记录来隐藏代码内部每个步骤的细节。

// cypress/support/index.js

/**
* Created by dell on 2020/6/9.
* 作者:上海-悠悠 交流QQ群:939110556
*/

Cypress.Commands.add('getIframeBody', () => {
// 定义getIframeBody方法
// and retry until the body element is not empty
return cy
.get('iframe', { log: false })
.its('0.contentDocument.body', { log: false }).should('not.be.empty')
.then((body) => cy.wrap(body, { log: false }))
})

这样重新运行,日志就会简洁一些了

关于cypress 处理iframe 相关资料https://www.cypress.io/blog/2020/02/12/working-with-iframes-in-cypress/
warp命令使用文档地址 https://on.cypress.io/wrap

(0)

相关推荐