Cypress用TypeScript写测试时beforeEach读fixture后后续步骤取值undefined如何解决
问题根因
- 你在
it测试用例中使用了箭头函数作为回调,箭头函数没有独立的this上下文,无法访问beforeEach中挂载到Cypress测试上下文对象上的属性。 - 只有用普通
function声明的测试回调、钩子回调,才能拿到Cypress注入的测试上下文this对象。
解决方法
方法1:调整回调函数为普通function,使用上下文挂载数据
将所有需要访问测试上下文的回调改为普通function声明即可:
describe(`test`, function () { beforeEach(function () { cy.fixture("testdata").then(function (data: any) { cy.log(`reading fixture file`); this.data = data; this.firstname = data.firstName; }); }); it(`testdata should be read`, function () { // 此时可正常访问this.firstname的值 expect(this.firstname).to.not.be.undefined; }); });
注意:所有需要访问测试上下文
this的回调,都不能使用箭头函数声明。
方法2:使用Cypress别名(更推荐,避免this指向问题)
不需要依赖this上下文,直接给fixture数据设置别名,调用时通过别名获取即可,适配TypeScript也更方便:
describe(`test`, () => { beforeEach(() => { // 给fixture数据设置别名 cy.fixture("testdata").as('testData'); }); it(`testdata should be read`, () => { // 通过别名读取数据 cy.get('@testData').then((data: any) => { const firstname = data.firstName; expect(firstname).to.not.be.undefined; // 后续业务逻辑写在该then回调内即可 }); }); });
- 该方法不需要修改回调函数的声明方式,不会出现this指向混乱的问题,是Cypress官方推荐的fixture标准使用方式。
内容的提问来源于stack exchange,提问作者FarFarAway
相关产品推荐
相关产品推荐

