Search code examples
testingautomated-testscypressfixtures

Cypress.io: How to use Fixtures?


I actually use the following code:

const userType = new Map([['Manager', '1'],['Developer', '2' ]]) 
for (const [key, value] of usertypes.entries()) 
{
    it('log in', () => 
    {
        cy.login(key,value)
        
        cy.xpath('path')
        .click()
         cy.xpath('path')                        
        .should('have.value' , key)         
    })
}

To use the Users in other tests I want to define usertypes in a fixture named users. How can I use this fixture with this test? My Json File looks like :

[[
     {"key": "Manager"},
     {"value": "1"}
],

[
    {"key": "Developer"},
    {"value": "2" }
]]

I tried to use cy.fixture in the beforeElse but I dont need this in every test and it was not right. How can I use the data of users.json in my test?


Solution

  • Looking at your test, the test data is defined outside the it(), so cy.fixture() will not be possible to call outside a running test. In this case I will recommend you to use import, so:

    1. Create a .js file(let's say in the fixtures folder) with your users (don't forget Map allows keys of any type, so no object notation needed):
    export const users =  [
        [
            "Manager", 1
        ],
    
        [
            "Developer", 2
        ]
    ]
    
    
    1. Import the variable and pass it as argument to your map constructor:
    import { users } from '../fixtures/your_file.js';
    
    
    const userCred = new Map(users);
       for (const [name, password] of userCred.entries()) {
           it('log in', () => {
               cy.login(name, password)
           })
       }