Skip to content

Instantly share code, notes, and snippets.

@iqbmo04
Created August 8, 2022 12:11
Show Gist options
  • Save iqbmo04/1dcb56845990018d1123d25f236b6dc5 to your computer and use it in GitHub Desktop.
Save iqbmo04/1dcb56845990018d1123d25f236b6dc5 to your computer and use it in GitHub Desktop.
cypress request with retries
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();
});
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