Cha*_*all 5 chai web-api-testing cypress
我使用Cypress作为 API 和 UI 测试的自动化框架。我已经编写了多个正在运行并通过的 API 测试,但它们只是验证返回response.status的200. 我想将来自 a 的响应 jsonGET与存储的“预期”响应进行比较,以确认 JSON 响应数据是正确的。
我在我的代码块中尝试了to.deep.equal和的不同变体。但我不想验证只有一个字段返回正确的值,我想验证一堆不同的字段是否返回正确的值。我的请求返回超过 100 行嵌套的 JSON 字段/值,而我只想验证彼此嵌套的 20 个左右的字段/值。deepEquals.then(response => {}GET
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
})
Run Code Online (Sandbox Code Playgroud)
错误=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');
Run Code Online (Sandbox Code Playgroud)
至于你的另一个问题,如果我理解正确的话,你的回答是这样的:
{
data: {
calculations: {
t_costs: [
{ comparison: { t_price: "1111" } },
{ comparison: { t_price: "2222" } },
{ comparison: { t_price: "3333" } },
{ comparison: { t_price: "4444" } },
/* ... */
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
您只想断言其中的一些t_costs对象。
为此,最好使用 chai 插件,例如debitoor/chai-subset。
设置方法:
const tPrice = response.body.data.calculations.t_costs[0].comparison.t_price
assert.equal(tPrice, '359701');
Run Code Online (Sandbox Code Playgroud)
在你的cypress/support/index.js:
{
data: {
calculations: {
t_costs: [
{ comparison: { t_price: "1111" } },
{ comparison: { t_price: "2222" } },
{ comparison: { t_price: "3333" } },
{ comparison: { t_price: "4444" } },
/* ... */
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
在你的规范中:
npm install --save-dev chai-subset
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10856 次 |
| 最近记录: |