如何使用 Cypress 断言搜索 JSON 响应

How to search through JSON response with Cypress assertions

考虑到下面的 API 响应,我想断言某个值在 JSON 结构中的确切位置。在我的例子中 name of pikachu in forms:

"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/"
}]

我想扩展下面的代码片段以不扫描整个 body 作为一个整体,因为响应中有很多 name,但是而是通过 forms 来准确定位它:

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' });
  });

非常感谢!

你能试试下面的代码,看看它是否有助于你的期望。从 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");
        })    
    });
})

到达 'forms' 只是链接另一个 its() 的问题,但 'include' 选择器似乎需要与数组中的对象完全匹配。

所以这行得通

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')
  })