如果想從頭學起Cypress,可以看下面的系列文章哦
https://www.cnblogs.com/poloyy/category/1768839.html
前言
- Cypress 6.0.0 開始不推薦使用 cy.server() 和 cy.route()
- 在將來的版本中,對 cy.server() 和 cy.route() 的支持將移至插件
- 現在優先考慮使用 cy.intercept()
作用
- 啟動服務器以開始將響應路由到 cy.route() 並更改網絡請求的行為
- 前置知識:熟悉 .route() 命令,https://www.cnblogs.com/poloyy/p/13852941.html
語法格式
cy.server()
cy.server(options)
options 參數
作用
- 作為默認值,它們被合並到 cy.route() 中
- 作為所有請求的配置行為
以下選項被合並為 cy.route() 的默認選項

以下選項控制服務器,將會影響所有請求的行為

命令執行結果
- 執行結果是 null
- 且后續不能再鏈接其他命令
沒有參數的栗子
// 啟動服務器 cy.server()
- 任何與 cy.route() 不匹配的請求都將傳遞到服務器,除非設置了 force404,這樣請求變成 404 和拿到一個空 response
- 與 options.ignore 函數匹配的任何請求都不會被記錄或存根(logged、stubbed)
- 將在命令日志中看到名為(XHR Stub)或(XHR)的請求
帶有參數的栗子
進入演示項目目錄下
注:演示項目是 cypress 提供的,如何下載可看 Cypress 系列文章的一開始幾篇都有寫
cd C:\Users\user\Desktop\py\cypress-example-recipes\examples\logging-in__xhr-web-forms
啟動演示項目
npm start
瀏覽器訪問項目
http://localhost:7079/
測試代碼
context('route 的栗子', function () { const username = 'jane.lane' const password = 'password123' before(function () { cy.visit('http://localhost:7079/') }) it('栗子1', function () { cy.server({ method: 'POST', status: 503, delay: 1000, headers: { 'x-token': 'abc-123-foo-bar' } }) cy.route({ url: '**/login', response: { success: false, data: 'Not success' }, }).as("login") cy.get("input[name=username]").type(username) cy.get("input[name=password]").type(`${password}{enter}`) cy.wait('@login').then((res) => { cy.log(res) expect(res.status).to.eq(503) expect(res.responseBody.data).to.eq('Not success') expect(res.responseHeaders).to.have.property('x-token', 'abc-123-foo-bar') }) }); })
測試結果

啟動服務器,關閉服務器的栗子
測試代碼
it('栗子2', function () {
cy.server()
cy.route({
url: '**/login',
method: 'POST',
status: 503,
response: {
data:"success"
}
}).as("login")
cy.get("input[name=username]").type(username)
//第一次發出請求
cy.get("input[name=password]").type(`${password}{enter}`)
cy.wait('@login').then((res) => {
expect(res.status).to.eq(503)
// 關閉服務器
cy.server({
enable: false
})
})
cy.visit('http://localhost:7079/')
cy.get("input[name=username]").type(username)
//第二次發出請求
cy.get("input[name=password]").type(`${password}{enter}`)
});
測試結果

第二個請求雖然被路由監聽到了,但是因為服務器關閉了,所以並沒有獲取路由的 status、response
注意事項
- 可以在啟動 cy.visit() 之前啟動服務器 cy.server()
- 通常,應用程序在加載時可能會立即發出初始請求(例如,對用戶進行身份驗證)
- Cypress 可以在 cy.visit() 之前啟動服務器並定義路由( cy.route() )
- 下次訪問時,服務器 + 路由將在應用程序加載之前立即應用
