I want to click a series of elements in a web page and check if each of those actions produces the correct API request URL. For that, I made an array of settings for each element and iterated over them, clicked the respective element and asserted the results. The problem is that the assertion for the last element always expects the setting for the first element. I see that this happens because cypress runs async. So, I ended up removing the iteration and just repeated all the action-assertions as shown below.
Is there an easy way to make a synchronous for loop instead of the way I have done it below ? Basically, I want to convert a sequence of .then() into a for loop. The "action" is the act of clicking an element on the page based on the actionSettings
object. That object can look something like {age: 23, gender: male}
. NOTE that I do not want to use the cypress recurse plugin here.
//code to intercept api call aliased as "actionApiCall".
cy.log("Do 1 of 5 actions on a given page")
.then(() => {
const actionSettings = getActionSettings("for action 1");
myPageObject
// clickElement(...) returns a Cypress.Chainable<null> with return cy.wrap(null);
.clickElement(actionSettings)
.wait("@actionApiCall")
.then((intercept) => {
// This assertion checks that the query params of the request URL are per the settings in actionSettings.
AssertActions.assertActionRequest(intercept.request, actionSettings);
});
}).log("Do 2 of 5 actions on a given page")
.then(() => {//do stuff})
.log("Do 3 of 5 actions on a given page")
.then(() => {//do stuff})
..... ETC
PS - Cypress .each
will not work here because I don't want to iterate over cypress elements. I want to iterate over an array of "actionSettings" i.e. not cypress elements. Also, here are the solutions that did not work for me.
How can I run a Cypress Command within a synchronous loop?
https://mcmap.net/q/449700/-cypress-io-writing-a-for-loop-closed
.then()
into a loop". – EhrenburgAssertActions.assertActionRequest
? i.e could you show roughly whatdo stuff
is for #2 & #3 please – Ehrenburg.then()
into a for loop. Do stuff for #2 & #3 is mostly the same as that for #1. The "action" is the act of clicking an element on the page based on the actionSettings object. That object can look something like{age: 23, gender: male}
. Please let me know if this helps or I need to explain it better. – Somewise['for action 1', 'for action 2', 'for action 3']
. Then I'd put the common code in a function and pass each action key in as a parameter (which is all simpleforEach()
code). I agree with comments about making assertions to "regulate" the flow, that seems like the right way to make the loop behave synchronously. – Ehrenburg