在Cypress Fixture中使用数组触发TypeError错误求助
问题分析与解决方案
你遇到的TypeError: Cannot read properties of undefined (reading 'assets')本质是第二个测试用例中this.value变为undefined,导致无法访问assets属性。虽然你在before钩子中把fixture数据挂载到了this.value,但Cypress的上下文绑定有时会因异步执行或测试隔离出现意外丢失,跨测试用例(it块)访问时更容易出现这个问题。
修复代码(使用闭包变量替代this)
最可靠的解决方式是在describe作用域内定义闭包变量存储fixture数据,避免上下文丢失:
/// <reference types="cypress" /> describe('Getting the names of the assets and iterating to find repeated names', ()=> { // 在describe作用域定义闭包变量 let userData; before(function() { cy.fixture('userdata').then(data => { // 将fixture数据赋值给闭包变量 userData = data; // 可选:打印确认数据加载成功 cy.log('Fixture data loaded:', userData); }) }) it('login',function() { cy.visit('https://sample-staging.com/login') cy.url().should('include','staging') // 使用闭包变量访问字段 cy.get('input[type="email"]').type(userData.email).should('have.value',userData.email) cy.get('input[type="password"]').type(userData.password).should('have.value',userData.password) cy.get('button').contains('Login').click() cy.wait(5000) cy.url().should('include',userData.title) }) it('Creating a new playlist', function() { cy.get('.text-xfm').contains('PLAYLISTS').click() cy.wait(5000) cy.get('div.text-xfs').contains('Add New').click() cy.get('label.text-xfx').should('contain','Playlist name is required') cy.get('#playlistName').type('Test-Playlist').should('have.value','Test-Playlist') cy.get('span.text-xfs').should('have.text','Choose assets to add to playlist').click() cy.wait(5000) cy.get('div.overflow-scroll').should('be.visible') // 现在可正常访问assets数组 cy.log(userData.assets) userData.assets.forEach(element => { cy.selectAsset(element) }); }) })
额外检查点
- 确认自定义命令
selectAsset定义在cypress/support/commands.js中(你提到的commands.json应该是笔误),且已在support/index.js中引入。 - 若仍有问题,可在
before钩子中添加断言确保fixture加载正常:before(function() { cy.fixture('userdata').then(data => { userData = data; expect(userData).to.have.property('assets').that.is.an('array'); }) })
内容的提问来源于stack exchange,提问作者Sreenivasan
相关产品推荐
相关产品推荐

