skip to Main Content

I’m trying to get data from a json file to use in my test, but it always gives me an error saying it can’t be fetched. I checked a lot of things on the internet, a lot of videos, personally I can’t find my problem.

  • Cypress version 13.06

fixture file call "userData.json":

{
  "userName": "John"
}

describe block:

describe("Cypress Test", () => {
  beforeEach(function () {
    cy.fixture("userData").then((userData) => {
      this.data = userData;
      cy.visit("WEBSITE");
    });
  });

My test:

 it("Handling FIXTURE", () => {
   cy.get('input[name="name"]').type(this.data.userName);
  });

The error:

TypeError
cy.xpath is not a function
cypress/e2e/dropDownFeatures.cy.js:86:8
  84 | 
  85 |   it("Handling FIXTURE", () => {
> 86 |     cy.get('input[name="name"]').type(this.data.userName);
     |        ^
  87 |   });
  88 | });
  89 | 

enter image description here
enter image description here

this.data.userName => to feed the data from the file to the field I use it for

2

Answers


  1. This is related to to the scope of the this.data variable. When using arrow functions, the this value is inherited from the enclosing lexical scope1. You can convert this to a regular function to fix the issue. Something like:

    // ...Rest
    
      it("Handling FIXTURE", function () { // <---- a regular function
        cy.get('input[name="name"]').type(this.data.userName);
      });
    });
    
    Login or Signup to reply.
  2. You can set the fixture on the global scope of the test

    let data;
    
    describe("Cypress Test", () => {
      beforeEach(function () {
        cy.fixture("userData").then((userData) => {
          data = userData;
        });
        cy.visit("WEBSITE");
      })
    
     it("Handling FIXTURE", () => {
       cy.get('input[name="name"]').type(data.userName);
      });
    })
    

    Or read it in using require()

    const data = require('cypress/fixtures/userData.json')
    
    describe("Cypress Test", () => {
      beforeEach(function () {
        cy.visit("WEBSITE");
      })
    
     it("Handling FIXTURE", () => {
       cy.get('input[name="name"]').type(data.userName);
      });
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search