我如何在赛普拉斯断言中部分比较深度嵌套的对象?

How do I partially compare deeply nested objects in Cypress assertions?

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

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

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 }

在您的示例中,您将对象 { 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 个对象中的几个。

为此最好使用 chai 插件,例如 debitoor/chai-subset

设置:

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" } }
    ]);