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

如何在Cypress中读取Fixture JSON文件?排查读取失败报错

Cypress读取Fixture JSON报错:Cannot read properties of undefined (reading 'users')

问题描述

在Cypress测试用例中尝试从JSON fixture文件读取数据时,出现报错Cannot read properties of undefined (reading 'users'),错误指向代码中this.userData未定义。

相关代码片段

测试用例代码

describe('Test for user data via JSON', ()=> {

    // Use the cy.fixture() method to pull data from fixture file
    before(function () {
        cy.fixture('users').then(function (userData) {
            this.userData = userData;
        })
    })

    it.only('Login Test. User1', () => {
        
        cy.wait(500)
        cy.visit('http://localhost/')

        cy.wait(500)

        onLoginPage.usernameInput(this.userData[0].username)
        onLoginPage.passwordInput(this.userData[0].password)
        onLoginPage.buttonGo()

    })
})

Fixture文件(users.json)

[
    {
        "id": 0,
        "username": "User1",
        "password": "password1",
        "_comment": "All rights"
    },
    {
        "id": 1,
        "username": "User2",
        "password": "password2",
        "_comment": "All rights"
    },
    {
        "id": 2,
        "username": "User3",
        "password": "password3",
        "_comment": "Reading only"
    }
]

解决方案

1. 修复it块的函数类型(最可能原因)

it块使用箭头函数时,不会绑定Cypress的测试上下文,导致this.userData无法访问到before钩子中挂载的数据。将it块的箭头函数改为普通函数即可:

describe('Test for user data via JSON', () => {

    before(function () {
        cy.fixture('users').then(function (userData) {
            this.userData = userData;
        })
    })

    it.only('Login Test. User1', function () { // 替换箭头函数为普通函数
        cy.wait(500)
        cy.visit('http://localhost/')

        cy.wait(500)

        onLoginPage.usernameInput(this.userData[0].username)
        onLoginPage.passwordInput(this.userData[0].password)
        onLoginPage.buttonGo()

    })
})

2. 检查Fixture文件路径

确保users.json位于Cypress默认的cypress/fixtures目录下。如果你的Fixture文件夹不在默认位置:

  • 可以在cypress.config.js中配置fixturesFolder指定路径;
  • 或者在cy.fixture中使用正确的相对路径,比如Fixture文件夹在项目根目录下的fixtures,则路径应为cy.fixture('../fixtures/users')(相对路径基于cypress目录)。

3. 替代方案:使用闭包变量存储数据

如果不想处理this上下文,可以在describe块内定义闭包变量,直接存储Fixture数据:

describe('Test for user data via JSON', () => {
    let userData; // 定义闭包变量

    before(function () {
        cy.fixture('users').then(data => {
            userData = data; // 赋值给闭包变量
        })
    })

    it.only('Login Test. User1', () => { // 此处可正常使用箭头函数
        cy.wait(500)
        cy.visit('http://localhost/')

        cy.wait(500)

        onLoginPage.usernameInput(userData[0].username)
        onLoginPage.passwordInput(userData[0].password)
        onLoginPage.buttonGo()
    })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 00:01:02