考虑到下面的API响应,我想断言JSON结构中某个值的确切位置。就我而言,表格中的pikachu名称如下:
"abilities": [
{
"ability": {
"name": "lightning-rod",
"url": "https://pokeapi.co/api/v2/ability/31/"
},
"is_hidden": true,
"slot": 3
},
{
"ability": {
"name": "static",
"url": "https://pokeapi.co/api/v2/ability/9/"
},
"is_hidden": false,
"slot": 1
}
],
"base_experience": 112,
"forms": [
{
"name": "pikachu",
"url": "https://pokeapi.co/api/v2/pokemon-form/25/"
}]我想在下面扩展代码片段,使其不作为一个整体扫描整个身体,因为响应中有很多名称,而是通过表单精确地找到它:
describe('API Testing with Cypress', () => {
var baseURL = "https://pokeapi.co/api/v2/pokemon"
beforeEach(() => {
cy.request(baseURL+"/25").as('pikachu');
});
it('Validate the pokemon\'s name', () => {
cy.get('@pikachu')
.its('body')
.should('include', { name: 'pikachu' })
.should('not.include', { name: 'johndoe' });
});事先非常感谢!
发布于 2020-01-21 11:48:40
获取“forms”只是链接另一个its()的问题,但是“包含”选择器似乎需要与数组中的对象完全匹配。
所以这起作用了
it("Validate the pokemon's name", () => {
cy.get("@pikachu")
.its("body")
.its('forms')
.should('include', {
name: 'pikachu',
url: 'https://pokeapi.co/api/v2/pokemon-form/25/'
})
})或者如果你有这个名字,
it("Validate the pokemon's name", () => {
cy.get("@pikachu")
.its("body")
.its('forms')
.should(items => {
expect(items.map(i => i.name)).to.include('pikachu')
})
})你可以断言消极的一面,
.should(items => {
expect(items.map(i => i.name)).to.not.include('johndoe')
})发布于 2020-01-21 04:01:47
你能不能试试下面的代码,看看它是否对你的期望有帮助。从response你可以得到如下的名字;
describe('API Testing with Cypress', () => {
var baseURL = "https://pokeapi.co/api/v2/pokemon"
beforeEach(() => {
cy.request(baseURL+"/25").as('pikachu');
});
it('Validate the pokemon\'s name', () => {
cy.get('@pikachu').then((response)=>{
const ability_name = response.body.name;
expect(ability_name).to.eq("pikachu");
})
});
})

https://stackoverflow.com/questions/59823535
复制相似问题