【问题标题】:How can I validate that the response of API has unique IDs while doing API Automation?在进行 API 自动化时,如何验证 API 的响应是否具有唯一 ID?
【发布时间】:2021-01-04 04:16:15
【问题描述】:

我正在使用赛普拉斯实现 API 自动化。我想验证这些响应的“id”是唯一的。 以下是 API 的示例响应

{
 "data": 
    [
        {
            "id": 5,
            "created": "2021-01-04T03:50:03.458+05:30"
        },
        {
            "id": 7,
            "created": "2021-01-04T03:50:03.469+05:30"
        },
        {
            "id": 8,
            "created": "2021-01-04T03:50:03.474+05:30"
        }
    ]
}

我们将不胜感激任何建议或想法。谢谢。

【问题讨论】:

    标签: api automation cypress unique-id


    【解决方案1】:

    还有更多的选择,你可以使用Set:

    const data = {
        "data": [
            {
                "id": 5,
                "created": "2021-01-04T03:50:03.458+05:30"
            },
            {
                "id": 7,
                "created": "2021-01-04T03:50:03.469+05:30"
            },
            {
                "id": 8,
                "created": "2021-01-04T03:50:03.474+05:30"
            }
        ]
    };
    
    const ids = data.data.map(e => e.id);
    const setIds = new Set(ids);
    expect(ids.length).to.equal(setIds.size);
    

    Set 将始终只包含唯一值,因此如果您在原始数据结构中没有唯一 id,则 set 对象将具有更少的元素。

    【讨论】:

      【解决方案2】:

      例如,一个想法可能是预取 before 中的所有 Id 并将它们存储到一个变量中,然后在 expect.to.be.oneOf 中使用此变量。

      这样做的一个缺点是,如果返回的数据集非常大,那么这可能会导致测试运行时间超过应有的时间。

      下面的代码展示了如何实现这一点。

      请注意,它以正文中的特定 ID 为目标(通过执行 res.body[2].id 即,它获取数据中的第三项)。如果您想测试整个响应,那么您可以再次通过列表 map (actualIdList = res.body.map((result) => result.id);) 并将其存储到另一个变量,然后对其进行断言(使用 expect(actualIdList).to.include.members(idList);)。

      describe('API Test', () => {
        let idList;
      
        before('should get some data', () => {
          cy.request({
            method: 'GET',
            url: myUrl
          }).then((res) => {
            idList = res.body.map((results) => results.id);
          });
        });
      
        it('should validate an Id in the response', () => {
          cy.request({
            method: 'GET',
            url: myUrl,
          }).then((res) => {
            expect(res.body[2].id).to.be.oneOf(idList);
          });
        });
      });
      

      【讨论】:

        猜你喜欢
        • 2012-11-10
        • 2019-08-06
        • 2017-02-23
        • 2023-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-09
        • 2018-06-17
        相关资源
        最近更新 更多