我将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 }
在你的示例中,你正在将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" } }
]);
这很棒。非常感谢你的帮助。它比我制作的要简单得多哈哈。
请记住,
chai-subset
可以工作,但是错误报告很糟糕。您需要手动分析失败的原因。没有何处字段不匹配的显式错误。