I'm doing a PUT request to an API, then I'm doing a GET request to see if what I PUT is there. The problem is that the API can take time between the PUT and GET requests for the data to propagate to be seen by the GET request. The testing framework I am using I just added waits, but I know this is not desirable, and I'm already seeing slow or failing tests as a result. To try to remove the waits I added the following, but I'm wondering if there is a cleaner way to do this?
// A function that simply tries x times for the checkingFunction to return a truthy value.
async function waitForCorrectApiResponse(checkingFunction, maxTries = 5, waitPeriod = 3000) {
let tries = 0;
while(maxTries > tries) {
const apiResponse = await checkingFunction();
if(apiResponse) {
return apiResponse;
}
// A wait method
await t.wait(waitPeriod);
tries ++;
}
}
const response = waitForCorrectApiResponse(async function(){
const apiResponse = await getApiResponse() // some random get API response function
if (apiResponse.body.hasOwnProperty('whatever') {
return apiResponse;
}
}
// Then do Chai assertions against response.....
For example off the top of my head I would like to be able to do something like the following...Basically, try a set of Chai assertions against a value x times, and each time if false reset the value.
async function waitForCorrectApiResponse(checkingFunction, maxTries = 5, waitPeriod = 3000) {
let tries = 0;
while(maxTries > tries) {
const apiResponse = await checkingFunction();
if(apiResponse) {
return apiResponse;
}
// A wait method
await t.wait(waitPeriod);
tries ++;
}
}
const response = waitForCorrectApiResponse(async function(){
const apiResponse = await getApiResponse() // some random get API response function
Chai.expect(apiResponse).to.have.property('whatever');
// Rest of Chai assertions.....
}
Aucun commentaire:
Enregistrer un commentaire