I'm trying to intercept API call which is autorefreshed each 10s by using cy.intercept()
in a loop. The loop should break when the status is set to "completed". Unfortunately cy.intercept()
is called only once, I tried to debug it and I can see in the console that the function is called only once and then breaks even though the status is not set to "completed". What am I doing wrong?
export function stubBackendResponse(id: string): void {
let iterations = 0;
const maxIterations = 10;
const intervalMs = 30000;
function checkStatusAndLoop(): void {
cy.intercept({
method: "GET",
url: `/api/${id}`,
}).as("data");
cy.wait("@data")
.its("response.body")
.should((data) => {
const status = data[0].status;
if (status !== "completed" && iterations < maxIterations) {
iterations++;
setTimeout(checkStatusAndLoop, intervalMs);
} else if (
status !== "completed" &&
iterations >= maxIterations
) {
throw new Error("Max iterations reached. Status is not 'completed'.");
}
});
}
checkStatusAndLoop();
}