Pulling data from fixture error : Cannot read property 'key' of undefined

When I tried to pull data from fictures into my test case I got an Cannot read property ‘key’ of undefined
error message.

Code:
describe(‘My First Test’, () => {

beforeEach(function() {
    cy.fixture("DataFile").then((data) => {
      this.key = data
      
    })
  })

it('Does not do much!', () => {
    cy.visit('https://rahulshettyacademy.com/angularpractice/')
    cy.get("form input[name='name']").type(this.key.Name)
    cy.get("form input[name='email']").type(this.key.Email)
   cy.get("#exampleInputPassword1").type(this.login.key.Password)
   cy.get('select').select(this.key.Gender)

})

Error:
Cannot read property ‘key’ of undefined

enter image description here

11 thoughts on “Pulling data from fixture error : Cannot read property 'key' of undefined”

  1. To access properties of this, use a function instead of an arrow function

    it('Does not do much!', function() {              // function here gets correct 'this'
      cy.visit('https://rahulshettyacademy.com/angularpractice/')
      cy.get("form input[name='name']").type(this.key.Name)
      cy.get("form input[name='email']").type(this.key.Email)
      cy.get("#exampleInputPassword1").type(this.login.key.Password)
      cy.get('select').select(this.key.Gender)
    })
    

    or you can move the fixture closer to the tests (less optimal but overall not by much)

    it('Does not do much!', () => {
      cy.fixture("DataFile").then((data) => {
        cy.visit('https://rahulshettyacademy.com/angularpractice/')
        cy.get("form input[name='name']").type(data.key.Name)
        cy.get("form input[name='email']").type(data.key.Email)
        cy.get("#exampleInputPassword1").type(data.login.key.Password)
        cy.get('select').select(data.key.Gender)
      })     
    })
    
    Reply

Leave a Comment