最近在用cypress做Web UI自动化,以前用selenium做UI自动化的时候用的最多就是PO模式,现在用cypress做Web UI自动化后,刚开始也是按照selenium那样使用PO模式编写测试用例,发现不是很好用,每个测试文件都要导入一次对Page Object,后来发现cypress不推荐使用PO模式,推荐使用自定义命令,以登录为例子。
不使用自定义命令
/// <reference types="cypress" />
describe("登录jenkins",function(){
it("登录jenkins成功",function(){
let usernameLocator = "#j_username"
let passwordLocator = "body > div > div > form > div:nth-child(2) > input"
let loginBtnLocator = "Sign in"
let loginUserNameLocator = "#header > div.login.page-header__hyperlinks > a.model-link.inside.inverse > span"
cy.visit("http://172.16.1.155:8080/login")
cy.get(usernameLocator).clear().type('Alfred')
cy.get(passwordLocator).clear().type('alfred1106')
cy.contains(loginBtnLocator).click()
cy.get(loginUserNameLocator).should('contain.text','Alfredfu')
})
})
使用自定义命令
新建自定义命令,在support/command.js,编写如下代码,新增了自定义命令login
Cypress.Commands.add('login',(username,password)=>{
let usernameLocator = "#j_username"
let passwordLocator = "body > div > div > form > div:nth-child(2) > input"
let loginBtnLocator = "Sign in"
cy.visit("http://172.16.1.155:8080/login")
cy.get(usernameLocator).clear().type(username)
cy.get(passwordLocator).clear().type(password)
cy.contains(loginBtnLocator).click()
})
2.使用自定义改写登录测试用例,通过cy.login(username,password)使用,代码如下
/// <reference types="cypress" />
describe("登录jenkins",function(){
it("登录jenkins成功",function(){
let loginUserNameLocator = "#header > div.login.page-header__hyperlinks > a.model-link.inside.inverse > span"
cy.login("Alfred","alfred1106")
cy.get(loginUserNameLocator).should('contain.text','Alfredfu')
})
})
今天就分享到这里啦!
本文分享自 暴走的软件测试Tester 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有