使用 cypress 进行 api 测试时,用于检查下面正文中的顺序的断言是什么

问题描述 投票:0回答:2

这是要重新排序的主体。我如何进行断言来检查

array[3]

中的特定顺序
{
                      "dimName": "Women's Clothing",
                      "dimOrder": 2,
                      "dimType": "wa",
                      "dimId": "category#womens-clothing",
                      "dimParent": "category"
                    },
                    {
                      "dimName": "Jewelry 1",
                      "dimOrder": 1,
                      "dimType": "wa",
                      "dimId": "category#jewelry",
                      "dimParent": "category"
                    },
                    {
                      "dimName": "Handbags",
                      "dimOrder": 3,
                      "dimType": "wa",
                      "dimId": "category#handbags",
                      "dimParent": "category"
                    }
cypress e2e-testing web-api-testing
2个回答
0
投票

如果您在 API 测试中收到上述 json 响应,请看几个简单示例:

检查id的顺序是这样的

cy.request(...)
  .then(response => {
    expect(response[0].dimId).to.eq('category#womens-clothing')
    expect(response[1].dimId).to.eq('category#jewelry')
    expect(response[2].dimId).to.eq('category#handbags')
  })

检查

dimOrder
字段是否是这样连续的

cy.request(...)
  .then(response => {
    const dimOrder = response.map(item => item.dimOrder)
    expect(dimOrder).to.deep.eq([1,2,3])        // deep because is array matching
  })

0
投票

为了更轻松地对响应进行断言,尤其是嵌套属性,您可以使用

cy-spok
。理解起来也更快。

const spok = require('cy-spok')

cy.request(...)
  .its('response.body')
  .should(spok({
     propertieWithArray: [
       {
         // you can assert the properties equal exact values
         dimName: "Women's Clothing", 
         dimOrder: 2,
         dimType: "wa",
         dimId: "category#womens-clothing",                      
         dimParent: "category" 
       },
       {
         // you can assert properties meet specifications
         dimName: spok.string, // Jewelry 1
         dimOrder: spok.number, // 1
         dimType: spok.type('string'), // wa
         dimId: spok.startsWith('category'), // category#jewelry
         dimParent: spok.endsWith('category') // category
       },
       {
         // use combination
         dimName: spok.string,
         dimOrder: spok.gt(0),
         dimType: "wa",
         dimId: spok.test(/#/),
         dimParent: "category"
       }
© www.soinside.com 2019 - 2024. All rights reserved.