前言
iframe 是一种常见的 web 页面上遇到的场景,像有些网站的登陆就是放到 iframe 里面的。
cypress 如何处理 iframe 上的元素呢,cypress 目前没有提供相似 selenium 上的 switch_to.frame 这种直接切换的方法,得本身封装一个操做方法。
web
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 上的操做没法使用快照功能spa
自定义命令
咱们可能会在多个测试用例访问iframe的元素,所以在 cypress 自定义命令 cypress/support/index.js
的文件里面添加一个命令。
自定义命令将自动在全部用例文件中使用,由于支持文件与每一个用例文件串联在一块儿。
3d
// 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() }) })
运行结果
code
禁用log
咱们能够经过禁用内部命令的日志记录来隐藏代码内部每一个步骤的细节。blog
// 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 })) })
这样从新运行,日志就会简洁一些了element
关于cypress 处理iframe 相关资料https://www.cypress.io/blog/2020/02/12/working-with-iframes-in-cypress/
warp命令使用文档地址 https://on.cypress.io/wrap
文档