Created
August 8, 2022 12:11
-
-
Save iqbmo04/1dcb56845990018d1123d25f236b6dc5 to your computer and use it in GitHub Desktop.
cypress request with retries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Cypress.Commands.add('retryRequest', (url, options) => { | |
Cypress._.defaults(options, { | |
method: 'GET', | |
body: null, | |
headers: { | |
'content-type': 'application/json' | |
}, | |
retries: 0, | |
function: false, | |
timeout: 0 | |
}); | |
let retriesCounter = 0; | |
function makeRequest() { | |
retriesCounter += 1; | |
cy.request({ | |
method: options.method || 'GET', | |
url: url, | |
headers: options.headers, | |
body: options.body, | |
failOnStatusCode: false | |
}).then(response => { | |
try { | |
if (options.function) { | |
options.function(response); | |
} | |
return cy.wrap(response); | |
} catch (err) { | |
if (!options.function) { | |
throw err; | |
} | |
if (retriesCounter >= options.retries) { | |
throw new Error( | |
`Failed to request ${url} after ${options.retries} retries` | |
); | |
} | |
cy.wait(options.timeout); | |
return makeRequest(); | |
} | |
}); | |
} | |
makeRequest(); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
context('Testing API call with retry', () => { | |
it('should retry this request', () => { | |
cy.retryRequest('https://www.google.com/', { | |
retries: 10, | |
function: function(response) { | |
if (response.status === 200) { | |
throw new Error(`still wrong status`); | |
} | |
}, | |
timeout: 2000 | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment