Search code examples
javascriptjsoncypressfixtures

How to read the fixture JSON file in Cypress?


I want to read data from a JSON fixture file in Cypress in my test cases.

For whatever reason it does not work. I followed several instructions and examples and simply do not make it work. What am I doing wrong?

Here are my files and code snippets.

TEST CASE:

describe('Test for user data via JSON', ()=> {

 
    // Use the cy.fixture() method to pull data from fixture file
    before(function () {
        cy.fixture('users').then(function (userData) {
            this.userData = userData;
            })
        })

    it.only('Login Test. User1', () => {
        
        cy.wait(500)
        cy.visit('http://localhost/')

        cy.wait(500)

        onLoginPage.usernameInput(this.userData[0].username)
        onLoginPage.passwordInput(this.userData[0].password)
        onLoginPage.buttonGo()

    })
})

JSON FILE

file name: users.json

[
    {
        "id": 0,
        "username": "User1",
        "password": "password1",
        "_comment": "All rights"
    },
    {
        "id": 1,
        "username": "User2",
        "password": "password2",
        "_comment": "All rights"
    },
    {
        "id": 2,
        "username": "User3",
        "password": "password3",
        "_comment": "Reading only"
    }
]

The error message is: "Cannot read properties of undefined (reading 'users')" The error message marks the "u" oder "userData" from this:

onLoginPage.usernameInput(this.**u**serData[0].username) 

The fixture folder is hierarchically here: "../fixtures/users"

The examples that I have seen look so simple. No idea what am I missing here.

Thank you very much.


Solution

  • I found a solution via this post:

    How to Use cy.fixture along with Array when multiple records in JSON fixture file

    I meant this part:

    cy.fixture('testdata').then(testdata  => {
    
                const ModuleID = testdata[0].ModuleID 
                const LoginName = testdata[0].LoginName
                const gameid = testdata[0].gameid
    
            cy.get('#ModuleID').type(ModuleID)
            cy.get('#LoginName').type(LoginName)
            cy.get('#gameid').type(gameid)
            cy.get('#btnSubmit').click()
    

    This way I can read from my .json file.

    I did not do the beforeEach, I can work with this inside the test case.

    Thanx for everybody helping me.

    Case closed with this solution.