【问题标题】:How to search through JSON response with Cypress assertions如何使用赛普拉斯断言搜索 JSON 响应
【发布时间】:2020-01-20 12:42:08
【问题描述】:

考虑到下面的 API 响应,我想断言某个值在 JSON 结构中的确切位置。就我而言,formspikachuname

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

我想扩展下面的代码 sn-p 不扫描整个身体,因为响应中有很多 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' });
  });

提前非常感谢!

【问题讨论】:

  • 欢迎来到 Stack Overflow。我不明白您所说的“宁可通过表格准确定位”是什么意思?

标签: mocha.js chai cypress


【解决方案1】:

获取“表单”只是链接另一个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')
  })

【讨论】:

  • 谢谢,我真的很喜欢这个解决方案。正是我正在寻找的。我搞砸了 .its() 中的单引号和双引号。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    相关资源
    最近更新 更多