前言
cypress 不僅可以用瀏覽器訪問web頁面,也可以直接 cy.request() 發請求訪問接口。
在實際工作中,很多時候都需要先登錄,如果只是寫登錄頁面的案例,可以直接在web頁面操作。
如果是寫其他頁面的案例,需要依賴登錄,這時候應該是不需要再次重復打開頁面去登錄,正確的做法是在用例跑之前寫個前置,發登錄的請求,保存cookie,讓頁面保持登錄狀態。
登錄接口
以禪道網站為例,登錄的接口沒提供接口文檔的話,可以自己抓包獲取接口請求報文
使用fiddler抓包,獲取請求報告信息
POST http://localhost:8080/zentao/user-login.html HTTP/1.1
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: 49.235.92.12:8080
Content-Length: 85
account=admin&password=****123456&passwordStrength=1&referer=%2Fzentao%2F&keepLogin=1
接口返回
{"result":"success","locate":"\/zentao\/"}
cypress登錄腳本案例
使用request發post請求,如果是頁面的 form 表單請求,只需設置 form 為 true,這樣就能在頭部聲明body的請求參數類型 Content-Type: application/x-www-form-urlencoded
/**
* Created by dell on 2020/6/4.
* 作者:上海-悠悠 交流QQ群:939110556
*/
describe('cypress request login zentao',function(){
it('login zentao',function(){
cy.request({
url:'http://localhost:8080/zentao/user-login.html',
method:'POST',
form:true, // indicates the body should be form urlencoded and sets Content-Type: application/x-www-form-urlencoded headers
headers: {
"X-Requested-With": "XMLHttpRequest"
},
body: {
"account": "admin",
"password": "****123456",
"passwordStrength": "1",
"referer": "/zentao/",
"keepLogin": "1"
}
})
.then((resp) => {
// assert status code is 200
expect(resp.status).to.eq(200)
// assert body contains success
expect(resp.body).to.contains("success")
})
})
})
運行結果
點 REQUEST 這一行可以直接查看到請求和返回的接口信息,查看起來還是很方便的
自定義登錄指令
cypress.json設置baseUrl地址
{
"baseUrl": "http://localhost:8080",
}
登錄的請求完成了,接下來我們會想后面的用例都需要把登錄當成前置,這時候需自定義一個登陸指令
在support/commands.js 下定義一個命令'login_request'用於發登錄請求
/**
* Created by dell on 2020/6/4.
* 作者:上海-悠悠 交流QQ群:939110556
*/
Cypress.Commands.add('login_request', (account="admin",
password="****123456") => {
cy.request({
url:'/zentao/user-login.html',
method:'POST',
form:true,
headers: {
"X-Requested-With": "XMLHttpRequest"
},
body: {
"account": account,
"password": password,
"passwordStrength": "1",
"referer": "/zentao/",
"keepLogin": "1"
}
})
.then((resp) => {
// status code is 200
expect(resp.status).to.eq(200)
// body contains success
expect(resp.body).to.contains("success")
})
})
request_login_zentao.js 用例設計
/**
* Created by dell on 2020/6/4.
* 作者:上海-悠悠 交流QQ群:939110556
*/
describe('cypress request login',function(){
before( function() {
cy.login_request()
})
it("訪問后台管理", function() {
cy.visit("/zentao/admin/")
cy.url().should('include', '/zentao/admin/')
cy.title().should('contain', '后台管理 - 禪道')
})
})
運行結果
多個用例直接共享cookies可以用白名單方式參考這篇https://www.cnblogs.com/yoyoketang/p/12931419.html