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

2022-02-27 00:00:00 json fixtures javascript cypress mocha.js

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行返回 {testdata.username=mytenant.admin||testdata.password=password} 具体从第3条记录提取


解决方案

在Cypress文档中,有两种方法描述了如何处理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中,您可以从Fixtures文件夹导入所有相关的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();
  })

相关文章