Hazem Alabiad
Hazem Alabiad

Reputation: 1052

Accessing fixture data inside `it` "a test case"

How can I access the following fixtures inside an it block:

users.json

{
"users": [
    {
        "first_name": "Fadi",
        "last_name": "Salam", 
        "work_email": "[email protected]"
    },
    {
        "first_name": "Maha",
        "last_name": "Black", 
        "work_email": "[email protected]"
    }
  ] 
}

My cypress related function code:

descibe('test', () => {
    beforeEach(function(){
    cy.restoreToken()
    cy.fixture('users.json').as('users')
    })

    it('Add an Employee', function() {
           cy.get('@users').then((users) => {
            const user_1 = users[0]
            cy.add_employee(user_1.first_name, user_1.last_name, user_1.work_email)
        }
    )}
})

I am unable to access first_name, ... etc

How can I do it?

Upvotes: 0

Views: 326

Answers (2)

gianegf
gianegf

Reputation: 18

If you want to access this fixure in all contexts and it blocks, you can do the following:

const USERS;

before (() => {
  cy.fixture('users.json').then(($users) => USERS = $users);
}

Then you access the const.

cy.getUserName().should('have.text', USERS[0].first_name);

Upvotes: 0

Pigbrainflower
Pigbrainflower

Reputation: 500

I've changed a few typos in your code and make it work.

In your users.json file 'first_name' is nested under 'users'.

You can use users.users[0].first_name to access first_name. Sample code below,

cy.get('@users').then((users) => {
            console.log(users.users[0].first_name);
        })

The console would print 'Fadi' in your case.

Upvotes: 2

Related Questions