如何将 fixture/*.json 文件中的特定记录访问到 cypress 中的特定测试用例中?

How to access specific record from fixture/*.json file into sepcific test case in cypress?

testdata.json

[
    {
        "case_id": 1,
        "case": "Login with valid data as wholesaler",
        "username": "admin",
        "password": "password",
        "result": "pass"
    },
    {
        "case_id": 2,
        "case": "Login with valid data as reseller",
        "username": "myreseller.admin",
        "password": "password",
        "result": "pass"
    },
    {
        "case_id": 3,
        "case": "Login with valid data as subscriber",
        "username": "mytenant.admin",
        "password": "password",
        "result": "pass"
    }
]

login.spec.js

  before(() => {
    cy.fixture('testdata').then((datajson) => {
      testdata = datajson
      return testdata
    })
  })
------it blocks-----
  it.only('TC03 - Login with valid data as subscriber', () => {
    cy.login(testdata.username, testdata.password);                            
    cy.title().should('equal', 'Home');
    cy.logout();
-------more it blocks-------

如何正确使用它使得第2行returns {testdata.username = mytenant.admin || testdata.password = 密码} 专门从第三条记录中获取

您的 json 结构为一个数组,因此您需要使用索引从中获取元素或重组您的 testdata.json fixture。

试试这个:

it.only('TC03 - Login with valid data as subscriber', () => {
    cy.fixture('testdata').then((dataFixture) => {
        cy.login(dataFixture[2].username, dataFixture[2].password);
        cy.title().should('equal', 'Home');
        cy.logout();
    })
})

P.S。假设您的 testdata 是在文件顶部导入的。

你可以这样做:

describe('Some Test Suite', function () {
  beforeEach(function () {
    cy.fixture('testdata').then(function (testdata) {
      this.testdata = testdata
    })
  })

  it.only('TC03 - Login with valid data as subscriber', function () {
    cy.log(this.testdata[2].username) //prints mytenant.admin
    cy.log(this.testdata[2].password) //prints password
    cy.login(this.testdata[2].username, this.testdata[2].password)
    cy.title().should('equal', 'Home')
    cy.logout()
  })
})

确保您正在获取 beforeEach() 中的夹具文件,以便夹具可用于所有测试用例。

在赛普拉斯文档中,有两种方法描述了如何处理 fixtures 文件夹中的那些 JSON 文件:https://docs.cypress.io/api/commands/fixture#Examples

1.选项

使用 cy.fixture():

加载您的 testdata.json
cy.fixture('testdata.json').as('testdata');

2。选项(我的推荐)

在您的 login.spec.js 中,您可以从灯具文件夹导入所有相关的 json 文件:

import testdata from '../fixtures/testdata.json';

然后您可以直接使用它们,例如使用第一个用户的用户名和密码:

  it.only('TC03 - Login with valid data as subscriber', () => {
    cy.login(testdata[0].username, testdata[0].password);                            
    cy.title().should('equal', 'Home');
    cy.logout();
  })