【问题标题】:How do I partially compare deeply nested objects in Cypress assertions?如何部分比较赛普拉斯断言中的深层嵌套对象?
【发布时间】:2026-01-30 03:05:01
【问题描述】:

我使用Cypress 作为 API 和 UI 测试的自动化框架。我编写了多个正在运行和通过的 API 测试,但它们只是验证 response.status 返回 200。我想将来自 GET 的响应 json 与存储的“预期”响应进行比较,以确认 JSON 响应数据是否正确。

我在.then(response => {} 代码块中尝试了to.deep.equaldeepEquals 的不同变体。但我不想验证只有一个字段返回正确的值,我想验证一堆不同的字段是否返回正确的值。我的GET 请求返回超过 100 行嵌套的 JSON 字段/值,我只想验证嵌套在彼此内部的 20 个左右的字段/值。

cy.request({
    method: 'GET',
    log: true,
    url: 'https://dev.api.random.com/calculators/run-calculate/524/ABC',

    headers: {
        'content-type': 'application/json',
        'x-api-key': calcXApiKey
    },
    body: {}
}).then(response => {
    const respGet = response.body
    const tPrice = response.body.data.calculations.t_costs[0].comparison.t_price
    cy.log(respGet, tPrice)
    assert.deepEqual({
        tPrice
    }, {
        t_price: '359701'
    })
       // assert.equal(response.status, 200) -- This works great
})

错误=expected { tPrice: undefined } to deeply equal { t_price: 359701 }

【问题讨论】:

  • 对于任何未来的搜索者,除了deepEqual之外,还有一个叫做deepInclude的东西

标签: cypress chai web-api-testing


【解决方案1】:

在您的示例中,您将对象{ tPrice: tPrice }{ t_price: '359701' } 进行比较,这就是为什么它总是会失败,因为键不同(除了tPrice 变量值是undefined)。

如果您已经将 实际 值存储在变量中,则无需从中创建对象并使用 deepEqual。你可以这样做:

const tPrice = response.body.data.calculations.t_costs[0].comparison.t_price
assert.equal(tPrice, '359701');

关于你的另一个问题,如果我理解正确,你的回答如下:

{
  data: {
    calculations: {
      t_costs: [
        { comparison: { t_price: "1111" } },
        { comparison: { t_price: "2222" } },
        { comparison: { t_price: "3333" } },
        { comparison: { t_price: "4444" } },
        /* ... */
      ]
    }
  }
}

而您只想断言其中的几个 t_costs 对象。

为此,最好使用 debitoor/chai-subset 之类的 chai 插件。

设置:

npm install --save-dev chai-subset

在你的cypress/support/index.js:

const chai = require('chai');
const chaiSubset = require('chai-subset');
chai.use(chaiSubset);

在您的规范中:

/* ... */
expect( response.body.data.calculations.t_costs )
    .to.containSubset([
        { comparison: { t_price: "1111" } },
        { comparison: { t_price: "3333" } }
    ]);

【讨论】:

  • 这很好用。非常感谢你的帮助。这比我做的简单多了哈哈。
  • 请记住,chai-subset 有效,但错误报告很糟糕。您需要手动分析失败的原因。不存在 where 字段不匹配的显式错误。
最近更新 更多