You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中断言拦截请求中的嵌套数组与对象值

Cypress断言拦截PUT请求体指定字段的解决方案

问题背景

需要验证拦截到的PUT请求体中name: "NewName"和title: "STUB1-Draft"两个字段,不想通过deep.equal断言整个请求体,但使用链式.its方法无法正确定位目标值。

原测试代码

it.only('Check the requestbody', function () {
  cy.intercept('PUT', '**/api/assessmenttest/**', req => {
    req.reply({ statusCode: 200 });
  }).as('NewSectionAndItem');

  cy.wait('@NewSectionAndItem')
    .its('request.body.test')
    .its('testParts')
    .its('testSections')
    .its('name')
    .should('include', 'NewName');
  // cy.wait('@NewSectionAndItem').its('request.body.testParts').expect(arr_obj[1].name).to.equal('NewName')
});

错误原因

  1. 多余层级:原代码中request.body.test不存在,请求体直接包含testParts数组,无需额外的test层级。
  2. 数组未索引:testParts和testSections均为数组,必须通过索引或遍历定位到具体元素后,才能访问其属性,不能直接链式调用.its访问数组的属性。

解决方案

方法1:通过索引直接定位(适用于已知元素位置的场景)

利用数组索引精准定位目标字段,结合.its完成断言:

it.only('Check the requestbody', function () {
  cy.intercept('PUT', '**/api/assessmenttest/**', req => {
    req.reply({ statusCode: 200 });
  }).as('NewSectionAndItem');

  // 断言name字段
  cy.wait('@NewSectionAndItem')
    .its('request.body.testParts.0.testSections.1.name')
    .should('eq', 'NewName');

  // 断言title字段
  cy.wait('@NewSectionAndItem')
    .its('request.body.testParts.0.testSections.1.itemReferences.0.itemSummary.title')
    .should('eq', 'STUB1-Draft');
});

方法2:使用.then回调灵活断言(适用于未知元素位置或需要复杂判断的场景)

通过.then获取拦截对象后,手动遍历数组找到目标元素再断言,灵活性更高:

it.only('Check the requestbody', function () {
  cy.intercept('PUT', '**/api/assessmenttest/**', req => {
    req.reply({ statusCode: 200 });
  }).as('NewSectionAndItem');

  cy.wait('@NewSectionAndItem').then(interception => {
    const requestBody = interception.request.body;
    const targetTestSection = requestBody.testParts[0].testSections.find(section => section.name === 'NewName');
    
    // 验证目标section存在且name正确
    expect(targetTestSection).to.exist;
    expect(targetTestSection.name).to.equal('NewName');
    
    // 验证对应的title字段
    expect(targetTestSection.itemReferences[0].itemSummary.title).to.equal('STUB1-Draft');
  });
});

内容的提问来源于stack exchange,提问作者E. E. Ozkan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 14:20:32