亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

CypressIO 發出請求,然后使用響應傳遞給另一個函數來調用另一個請求,包裝在可重用函數中

CypressIO 發出請求,然后使用響應傳遞給另一個函數來調用另一個請求,包裝在可重用函數中

GCT1015 2023-07-29 15:31:24
所以我遇到的問題是我希望能夠調用一個模塊函數,然后調用 cy.request() 獲取響應并以一種很好的方式將其提供給另一個 cy.request() 。我想讓這段代碼變得更好:Cypress.Commands.add('createUser', (user) => {  cy.request({  method: 'POST',  url: 'https://www.example.com/tokens',  body: {    email: 'admin_username',    password: 'admin_password' }}).then((resp) => {   cy.request({     method: 'POST',     url: 'https://www.example.com/users',     headers: ({ Authorization: 'Bearer ' + resp.body.token }),     body: user  })})})我想在自己的函數中擁有兩個 cy.requests,例如 getAuthToken() 和 createUser(),這樣我可以將其包裝在 Cypress.Command 中,或者只是一個模塊函數并在測試文件中調用const seedUser = (userObject) => {             getAuthToken().then((token) => {                 return createUser(token); //where this would return the created user.             }                }然后在測試文件中像這樣使用before(()=>{    let user =  seedUser(); //or let user = cy.seedUser();}
查看完整描述

1 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

您可以使用cy.wrap()來包裝第一個請求的響應,然后您可以在任何地方使用它。

自定義命令:

Cypress.Commands.add('getAuthToken', () => {

? ? cy.request({

? ? ? ? method: 'POST',

? ? ? ? url: 'https://www.example.com/tokens',

? ? ? ? body: {

? ? ? ? ? ? email: 'admin_username',

? ? ? ? ? ? password: 'admin_password'

? ? ? ? }

? ? }).then((response) => {

? ? ? ? cy.wrap(response).as('getAuthTokenResponse')

? ? })

})



Cypress.Commands.add('createUser', (user) => {

? ? cy.get('@getAuthTokenResponse').then((resp) => {

? ? ? ? cy.request({

? ? ? ? ? ? method: 'POST',

? ? ? ? ? ? url: 'https://www.example.com/users',

? ? ? ? ? ? headers: ({ Authorization: 'Bearer ' + resp.token }),

? ? ? ? ? ? body: user

? ? ? ? })

? ? })

})

在您的測試文件中,您只需添加:


cy.getAuthToken()

cy.createUser(user)


查看完整回答
反對 回復 2023-07-29
  • 1 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號