Warm tip: This article is reproduced from serverfault.com, please click

api-如何部分比较赛普拉斯断言中的深层嵌套对象?

(api - How do I partially compare deeply nested objects in Cypress assertions?)

发布于 2019-08-28 17:19:35

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

代码块中尝试了to.deep.equal和的不同变体。但是我不想验证仅一个字段返回了正确的值,而是想验证一堆不同的字段是否返回了正确的值。我的请求返回了100行以上的嵌套json字段/值,而我只想验证彼此嵌套的20个左右的字段/值。 deepEquals.then(response => {}GET

*注意:忽略revId,它来自先前的请求。

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

    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 }

Questioner
Chase Small
Viewed
11
dwelle 2019-08-29 20:20:27

在你的示例中,你正在将object{ 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" } }
    ]);