Skip to content

Dynamically generate tests in Cypress to test your APIs

When you are using Cypress to test your APIs, you might face a scenario where you have a config or properties file and you want to use it to write your tests. But you don’t have to write a test for each and every item in the config file. Cypress lets your iterate over your config file and dynamically create tests at run-time.

Let’s assume we have a config file like this in JSON format.

{
    "api1": {
        "kpi": "api1",
        "url": "https://localhost/api/1"
    },
    "api2": {
        "kpi": "api2",
        "url": "https://localhost/api/2"
    },
    "api3": {
        "kpi": "api3",
        "url": "https://localhost/api/3"
    },
    "api4": {
        "kpi": "api4",
        "url": "https://localhost/api/4"
    },
    "api5": {
        "kpi": "api5",
        "url": "http://localhost/api/5"
    }
}

I’m going to create tests for each of the entries here.

    Object.keys(input).forEach((key) => {

        it("Testing - " + key, function () {
    
            cy.fixture('responses.json').then((responses) => {
    
                console.log("RES --- " + JSON.stringify(responses));
    
                cy.log(key)
                cy.log(input[key])
    
                let api = input[key];
                cy.request
                    ({
                        method: 'GET',
                        url: api.url,
                        headers: {
                            'authorization': 'Bearer ' + token
                        }
                    }).then((response) => {
                        cy.log(response.body);
                        expect(JSON.stringify(response.body.payload.data)).equal(JSON.stringify(responses[key].data));
                    })
    
                
    
            })
        })
    })

In your Cypress console, you can see the tests running for each entry in config JSON.

Testing api1
Testing api2
Testing api3
Testing api4
Testing api5
See also  Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout - How to fix?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.