【问题标题】:How to use cy.fixture to read multiple records from a json file如何使用 cy.fixture 从 json 文件中读取多条记录
【发布时间】:2020-05-01 01:41:20
【问题描述】:

我使用 cy.fixture() 编写了下面的代码来从 Json 文件中读取记录。

/// <reference types = "cypress" />
describe('Fixtures', () => {

before(() => {
    cy.viewport(1400, 800)
    cy.visit('https://www.adroll.com/')
})

it('Formulário de Cadastro', function() {

    cy.get(':nth-child(8) > .cta > span').click()

    cy.fixture('AdRoll').as('cadastro').then(() => {

        cy.get('#first_name').type(this.cadastro.FirstName)
        cy.get('#last_name').type(this.cadastro.LastName)
        cy.get('#email').type(this.cadastro.CompanyEmail)
        cy.get('#company_phone').type(this.cadastro.ComPhoNum)
        cy.get('#url').type(this.cadastro.CompWebSiteUrl) 
    })

}) 

})

cy.fixture()命令要读取的记录的Json文件的内容。

[
{
    "FirstName": "Leandro",
    "LastName": "Pereira",
    "CompanyEmail": "leandro.nares@gmail.com",
    "ComPhoNum": "991549450",
    "CompWebSiteUrl": "www.kyz.com.br"
},
{
    "FirstName": "Paulo",
    "LastName": "Nares",
    "CompanyEmail": "Paulo.nares@gmail.com",
    "ComPhoNum": "000000000",
    "CompWebSiteUrl": "www.paulo.com.br"
}
]

赛普拉斯在下图中显示错误消息。我相信发生错误是因为我正在从 Json 文件中读取多条记录,而我的代码无法读取数组。谁能帮我修改代码以读取 Json 文件中的所有记录?

【问题讨论】:

  • 如果你有一个数组,那么你需要索引数组的元素。因此,假设 JSON 文件根据 Cypress 是有效的,您应该使用 this.cadastro[0].FirstName 等访问您的数据。
  • 谢谢你,natn2323。您的建议部分有效,但实际上我的想法是脚本将循环,并读取每条记录并自动输入几个条目。与 Selenium 中的 DataDriven 相同。
  • 好的,那么此时您只需要遍历数组的长度即可。
  • natn2323,这就是问题所在,我不知道如何循环。你能帮忙做一个吗?
  • 你可以在 JavaScript 中做一个基本的 for 循环。见here。试一试。如果你不明白,你可能会在 StackOverflow 上找到与 JavaScript 中不同类型的循环有关的其他问题

标签: javascript json automated-tests cypress


【解决方案1】:

你可以做的是;在测试文件中包含您的固定装置,例如

const adRoll = require('../../fixture/TTT')

                   adRoll.forEach(function(input)
                {
                     const Firstname=input.Firstname
                     const Lastname=input.lastname
                    cy.get('#fname').type(Firstname)
                    cy.get('#lname').type(lasttname)
                    


                })

【讨论】:

  • 谢谢!在具有多个数据的单个夹具 JSON 中完美地为我工作,而不是在 describe('Test Single Input Field Form', function() declare : const testData = require("../../fixtures/multipleInputFields.json") 然后 testData.forEach((data) =&gt; { const message = data.message it('Test Case', function(){ cy.log("data is:" + data) cy.get('#user-message').type(message).should('have.value', message) cy.get('#get-input &gt; button').click() cy.wait(200) cy.get('span#display').should('have.text', message) }) });
猜你喜欢
  • 1970-01-01
  • 2020-05-21
  • 2015-04-25
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多