Cypress: Stubbing a particular key in JSON response

Viewed 376

I want to stub the following response in Cypress. Specifically stubbing the key ds_version, which could have a possible value of 0, 1, or 2. Each value would display a different element on the UI.

fixtures/user.json

{
"email": "test@test.com",
"firstName": "Test",
"lastName": "Test",
"ds_version": 0, --> switch this value to 0, 1, 2 for different test scenarios
"country": "Indonesia",
...
}

I was able to achieve this by providing the whole JSON as cy.route() parameter, like below:

cy.server();
cy.route('GET', '/users/current', 'fixture:user.json').as('getUsersCurrent');

It seems that if I want to test for ds_version=1 or ds_version=2, I would need to provide different JSON with changed value. Is there a way to provide a different ds_version value while the rest of JSON remain the same?

1 Answers

You can use the cy.route2() from cypress:

  1. Go to cypress.json and write "experimentalNetworkStubbing": true

  2. In your test.spec file write:

    cy.route2('GET', '/users/current', (req) => {
        req.reply((res) => {
            let list = JSON.parse(res.body)
            list.ds_version = 1
            res.send(list)
        })
    })
    
Related