前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Cypress web自动化33-cy.request()参数关联(上个接口返回数据传个下个接口)

Cypress web自动化33-cy.request()参数关联(上个接口返回数据传个下个接口)

作者头像
上海-悠悠
发布2020-06-10 15:39:14
1.6K0
发布2020-06-10 15:39:14
举报
文章被收录于专栏:从零开始学自动化测试

前言

接口自动化中最常见的问题就是参数关联:如何把上个接口返回数据传个下个接口当入参。 cy.request() 发请求时,可以用 .as() 方法保存上个接口返回的对象,方便后面的接口调用数据。

cy.request()

cy.request() 可以发送 XHR 请求 访问接口地址:https://jsonplaceholder.cypress.io/comments 接口返回数据

代码语言:javascript
复制
[
  {
    "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 结果断言

代码语言:javascript
复制
/**
 * 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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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() 生成接口返回对象关联案例

代码语言:javascript
复制
/**
 * 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() 别名保存响应数据,以便稍后在共享测试上下文中使用

代码语言:javascript
复制
/**
 * 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)
          })

    })

    })

运行结果

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-06-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 从零开始学自动化测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • cy.request()
  • 参数关联
  • .as() 别名使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档