Home > Enterprise >  Cypress cy.wait with alias
Cypress cy.wait with alias

Time:10-09

I would like to extract a big json file via API in Cypress. The following code (without the cy.wait()) works for small files. Once the file gets bigger and the response time grows over 30 seconds, the script times out.

Therefore I added cy.wait('@api_call')

describe('Api request', () => {
    it('get json', () => {
        cy.request({
            method: 'GET',
            url: '/api_endpoint',
            headers: {
                'API-KEY': 'xxxxxxxxxxxxxxxxx',
            }
        }).as('api_call')
        cy.wait('@api_call').its('response.body').should('contain','name')
                .then(response => {
            var someArr = new Array();
             someArr = response.body;
            cy.writeFile('cypress/fixtures/testdata.txt', someArr);
        })
    })
})

Now this throws the error

cy.wait() only accepts aliases for routes.

How can I correctly tell Cypress to wait for the request to resolve?

[edit]I have now tried adding every possible timeout setting from https://docs.cypress.io/guides/references/configuration#Timeouts and setting them to 90000ms, but it still would not increase the timeout. It still times out after 30 seconds.

CodePudding user response:

You can add a global timeout for responseTimeout in your cypress.json like:

{
  responseTimeout: 30000
}

Or, you can add timeout individually as well -

describe('Api request', () => {
  it('get json', () => {
    cy.request(
      {
        method: 'GET',
        url: '/api_endpoint',
        headers: {
          'API-KEY': 'xxxxxxxxxxxxxxxxx',
        },
        timeout: 30000
      },
    ).as('api_call')
    cy.get('@api_call')
      .its('response.body')
      .should('contain', 'name')
      .then((response) => {
        var someArr = new Array()
        someArr = response.body
        cy.writeFile('cypress/fixtures/testdata.txt', someArr)
      })
  })
})

CodePudding user response:

So it looks like my fault was how I used the timeout option

describe('Api request', () => {
    it('get json', () => {
        cy.request({
            method: 'GET',
            url: 'https://test.joulesapp.de/coreApi/v1/roles',
            headers: {
                'API-KEY': 'c0b4d303151e6bebf8251aafc1eb5bfb',
            },
            timeout: 90000 <-----
            },
        )
            .then((response) => {
                var someArr = new Array()
                someArr = response.body
                cy.writeFile('cypress/fixtures/testdata.txt', someArr)
            })
    })
})

If you put the timeout option there, it will work as intended.

Now it waits for up to 90s which is enough for my purposes.

  • Related