Cypress web自動化33-cy.request()參數關聯(上個接口返回數據傳個下個接口)


前言

接口自動化中最常見的問題就是參數關聯:如何把上個接口返回數據傳個下個接口當入參。
cy.request() 發請求時,可以用 .as() 方法保存上個接口返回的對象,方便后面的接口調用數據。

cy.request()

cy.request() 可以發送 XHR 請求
訪問接口地址:https://jsonplaceholder.cypress.io/comments
接口返回數據

[
  {
    "postId": 1,
    "id": 1,
    "name": "id labore ex et quam laborum",
    "email": "Eliseo@gardner.biz",
    "body": "laudantium enim quasi est quidem magnam voluptate ..."
  },
  {
    "postId": 1,
    "id": 2,
    "name": "quo vero reiciendis velit similique earum",
    "email": "Jayne_Kuhic@sydney.com",
    "body": "est natus enim nihil est dolore omnis voluptatem ..."
  }
.....
]

使用 cy.request() 發get請求,對 response 結果斷言

/**
 * Created by dell on 2020/6/5.
 * 作者:上海-悠悠 交流QQ群:939110556
 */


describe('network request', function() {

    it("network request", function()
    {
       cy.request('https://jsonplaceholder.cypress.io/comments')
           .should((response) => {
                expect(response.status).to.eq(200)
                expect(response.body).to.have.length(500)
                expect(response).to.have.property('headers')
                expect(response).to.have.property('duration')
          })
    })
    })

運行結果

參數關聯

將上個接口的 response 數據傳給下個請求
接口1:

GET https://jsonplaceholder.cypress.io/users?_limit=1
返回:
[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  }
]

接口2:

POST https://jsonplaceholder.cypress.io/posts
body:
{
      userId: user.id,
      title: 'Cypress Test Runner',
      body: 'Fast, easy and reliable testing for anything that runs in a browser.',
    }

接口返回
{
  "userId": 1,
  "title": "Cypress Test Runner",
  "body": "Fast, easy and reliable testing for anything that runs in a browser.",
  "id": 101
}

.its() 生成接口返回對象關聯案例

/**
 * Created by dell on 2020/6/5.
 * 作者:上海-悠悠 交流QQ群:939110556
 */


describe('network request', function() {

    it("pass the response data to the next request.", function()
    {
        // 先發一個請求,獲取返回的接口數據
        cy.request('https://jsonplaceholder.cypress.io/users?_limit=1')
          .its('body.0')   // 返回一個list,獲取list第一個對象
          .then((user) => {
            expect(user).property('id').to.be.a('number')
            // 發個新的post請求,userId用上個請求返回的數據
            cy.request('POST', 'https://jsonplaceholder.cypress.io/posts', {
              userId: user.id,
              title: 'Cypress Test Runner',
              body: 'Fast, easy and reliable testing for anything that runs in a browser.',
            })
          })
          // 注意這里的值是第二個請求的返回值
          // response 是一個新的 post對象
          .then((response) => {
            expect(response).property('status').to.equal(201) // new entity created
            expect(response).property('body').to.contain({
              title: 'Cypress Test Runner',
            })
            // 我們不知道實際response返回的id值是多少 - 但是我們可以判斷值 > 100
            // since JSONPlaceholder has built-in 100 posts
            expect(response.body).property('id').to.be.a('number')
              .and.to.be.gt(100)
            // we don't know the user id here - since it was in above closure
            // so in this test just confirm that the property is there
            expect(response.body).property('userId').to.be.a('number')
          })
    })

    })


運行結果

.as() 別名使用

還有更好的處理方式,可以使用.as() 別名保存響應數據,以便稍后在共享測試上下文中使用

/**
 * Created by dell on 2020/6/5.
 * 作者:上海-悠悠 交流QQ群:939110556
 */


describe('network request', function() {

    it("save the response data shared test context", function()
    {
        cy.request('https://jsonplaceholder.cypress.io/users?_limit=1')
          .its('body.0') // yields the first element of the returned list
          .as('user') // saves the object in the test context
          .then(function () {
            // NOTE 👀
            //  By the time this callback runs the "as('user')" command
            //  has saved the user object in the test context.
            //  To access the test context we need to use
            //  the "function () { ... }" callback form,
            //  otherwise "this" points at a wrong or undefined object!
            cy.request('POST', 'https://jsonplaceholder.cypress.io/posts', {
              userId: this.user.id,
              title: 'Cypress Test Runner',
              body: 'Fast, easy and reliable testing for anything that runs in a browser.',
            })
            .its('body').as('post') // save the new post from the response
          })
          .then(function () {
            // When this callback runs, both "cy.request" API commands have finished
            // and the test context has "user" and "post" objects set.
            // Let's verify them.
            expect(this.post, 'post has the right user id')
              .property('userId').to.equal(this.user.id)
          })

    })


    })

運行結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM