I'm trying to write code that will let the user specify the number of items to create via Cypress (this flexibility is needed for some of our tests).
function createSomeItems(itemCount, headers)
{
item: { id: 0, field1: 123, field2: "test text!"};
let chain;
for (let i = 0; i < itemCount; i++)
{
chain = cy.request({method: 'POST', url: '/create-item', body: item, headers: headers});
item.id += 1;
}
return chain;
}
The problem is that the application hits an error because of duplicate ID for the items. From what I can see, the call to cy.request does not actually execute when I think it does.
I'm still very new to Cypress (and this is the first time I've used JavaScript in about 15 years), so I'm not sure how to resolve this.
I know I could have n calls to cy.request().then()... chained together explicitly, though this will make the tests large and hard to read (especially for test cases that require larger values of n) and I'm trying to keep the code neat and compact.
For anyone who is curious, I came up with a solution that returns the chain of commands (unlike the example from Cypress):
function createSomeItems(itemCount, headers)
{
let item = { id: 0, field1: 123, field2: "test text!"};
function recursiveRequester(itemNumber, chain)
{
item.my_id = itemNumber;
return chain.then(() => {
return cy.request({method: 'POST', url: '/create-item', body: item, headers: headers});
.then(() => {
if (itemNumber === itemCount) {
return chain;
}
else {
return recursiveRequester(itemNumber + 1, chain);
}
})
})
}
return recursiveRequester(1, functionThatDoesOtherSetupwork());
}