【问题标题】:How can I assign a value of nested response json object to a variable by using Cypress & JavaScript?如何使用 Cypress 和 JavaScript 将嵌套响应 json 对象的值分配给变量?
【发布时间】:2022-10-13 21:33:55
【问题描述】:

如何将嵌套响应 json 对象的值分配给变量?例如;我在另一个 stackoverflow 问题下看到了类似问题的答案,但我在这个答案中看不到解决方案,以便将“虚拟 3”值设置为如下所示的变量。

const myVariable = cy.get('@sample')
    .its('body')
    .its('sample')
    .its('1')
    .its('names')
    .its(0).as('string')

响应 JSON:

{
  "sample": [
    { "names": ["Dummy 1", " Dummy 2"] },
    { "names": ["Dummy 3", " Dummy 4"] },
    { "names": ["Dummy 5", " Dummy 6"] }
  ]
}

数组中的最后一个对象应按如下方式访问:

// to check a child's length
  cy.get('@sample')
    .its('body') // 'responseBody' in case of latest cypress version
    .its('sample')
    .its('2')
    .its('names')
    .its('length')
    .should('eq', 2);

// To check content
  cy.get('@sample')
    .its('body') // 'responseBody' in case of latest cypress version
    .its('sample')
    .its('2')
    .its('names')
    .its(1)
    .should('include', '6');

【问题讨论】:

    标签: javascript cypress


    【解决方案1】:

    一旦你产生了身体,你就可以使用标准的 JS 函数来找到你的特定值。

    cy.get('@sample')
      .its('body')
      .then((body) => {
        return body.sample[2].names // return the array to the Cypress chain
      })
      .should('have.length', 2)
      .its(1)
      .should('contain', '6');
    

    您还可以为要在同一测试中使用的值设置别名,或将其存储为Cypress.env() 变量。

    // alias
    cy.get('@sample')
      .its('body')
      .then((body) => {
        return body.sample[2].names 
      }).as('someValue');
    
    // Cypress.env
    cy.get('@sample')
      .its('body')
      .then((body) => {
        Cypress.env('someValue', body.sample[2].names);
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 2023-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多