我正在尝试使用固定装置来保存不同测试的数据,这是代码示例。我得到'无法读取未定义的属性

I'm trying to use fixtures to hold data for different tests, This is an example of the code. where I'm getting 'Cannot read properties of undefined

我正在尝试使用固定装置来保存不同测试的数据,这是代码示例。当进行第二次测试时,我得到“无法读取未定义的属性(读取 'data')”。

/// <reference types="Cypress" />

describe('MyFirstTestSuite', () => {

    before(() => {
        // root-level hook
        // runs once before all tests
        cy.fixture('example').then(function(data) { 
          this.data=data
        });
      });

    it('FirstTest case', () => {
        cy.visit('https://rahulshettyacademy.com/angularpractice/')
        cy.get('').type(this.data.name)
        cy.get('Select').select(this.data.gender)  
    });
});

这是我的 environment.json 文件:

{
  "name" : "Darshit",
  "gender": "Male"
}

而不是

this.data=data

尝试使用

globalThis.data = data

如果要使用 this 关键字,则需要在某处定义 data。此外,您需要使用 traditional function expression because arrow functions do not have a this binding. You can easily accomplish this by using .as(). Filip Hric goes over different solutions in this blog post.

describe('MyFirstTestSuite', () => {

    before(() => {
        // root-level hook
        // runs once before all tests
        cy.fixture('example').as('data'); // change this to using an alias
      });

    it('FirstTest case', function() { // change this because `this` does not work with arrow functions
        cy.visit('https://rahulshettyacademy.com/angularpractice/')
        cy.get('').type(this.data.name)
        cy.get('Select').select(this.data.gender)  
    });
});

Cypress has more information on fixtures here.