You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress的spec文件中从fixture加载JSON数组并迭代?

解决Cypress从Fixture加载下拉选项数组的问题

问题根源

你遇到的引用错误主要来自两个点:

  1. Fixture的JSON结构嵌套了一层对象,导致无法直接获取目标数组
  2. 测试代码里没有正确引用Fixture中加载的变量,仍在使用硬编码数组

解决方案

方案1:简化JSON文件结构(推荐)

将fixture/report_types.json改成直接的字符串数组,去掉外层的对象包裹:

["Alarm","Alarm Trends","Analytics","Asset","Audit","Cross Sectional Benchmarking","Degree Days","Longitudinal Benchmarking"]

然后修改测试代码,正确加载并使用Fixture数据:

describe('Test Scenario DatePickers and Dropdowns', () => {
  before(function() {
    cy.get('#addReportButton').click()
    // 加载Fixture并设置别名
    cy.fixture('report_types').as('reportList')
  })

  it('Report Type dropdown is working', function() {
    // 从Fixture获取数组,注意用this.reportList(必须用普通function而非箭头函数)
    const reportList = this.reportList
    const reportLength = reportList.length

    cy.log("Pre condition: Should have Alarm as a default value")
    cy.get('#selectReportType').should('have.value', 'Alarm')

    // 迭代验证每个选项
    for (let index = 0; index < reportLength; index++) {
      const element = reportList[index]
      cy.get('#selectReportType')
        .select(element)
        .should('contain.text', element)
    }
  })
})

方案2:保留原有JSON结构

如果不想修改JSON文件,需要在代码中提取嵌套的reportname数组:

describe('Test Scenario DatePickers and Dropdowns', () => {
  before(function() {
    cy.get('#addReportButton').click()
    cy.fixture('report_types').as('reportData')
  })

  it('Report Type dropdown is working', function() {
    // 提取嵌套的reportname数组
    const reportList = this.reportData[0].reportname
    const reportLength = reportList.length

    cy.log("Pre condition: Should have Alarm as a default value")
    cy.get('#selectReportType').should('have.value', 'Alarm')

    for (let index = 0; index < reportLength; index++) {
      const element = reportList[index]
      cy.get('#selectReportType')
        .select(element)
        .should('contain.text', element)
    }
  })
})

关键注意事项

  • 必须使用普通function():在before和it中不能用箭头函数,否则无法通过this访问Fixture别名的变量
  • 异步顺序处理:Cypress会自动等待before块中的Fixture加载完成后,再执行it块的逻辑,无需额外处理异步
  • 断言适配:如果下拉框的实际value属性和显示文本不一致,需要调整断言逻辑,比如将should('contain.text', element)改为should('have.value', element),具体根据页面DOM结构判断

内容的提问来源于stack exchange,提问作者Avdhut Joshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:40:24