best-lunch-5240
02/02/2023, 9:53 PMcy.createUser() which implementation looks like this:
Cypress.Commands.add('createUser', (user: User, userNumber: number) => {
user.name = `User ${userNumber}`
cy.request({
method: 'POST',
url: '/createUserEndpoint',
body: user,
headers: {
authorization: 'token'
}
}).then(response => {
return response.body;
});
});
declare global {
namespace Cypress {
interface Chainable {
createUser(user: User, userNumber: number): Chainable<void>;
}
}
}
And in the test to create let's say 3 users one after another I have to do this:
import { userData } from '../../fixtures'
let user: User = JSON.parse(JSON.stringify(userData));
it('test', () => {
cy.createUser(user, 1)
.createUser(user, 2)
.createUser(user, 3);
)};
But is it possible to create a custom command which would chain these commands inside it?
Something like:
Cypress.Commands.add('createUsers', (user: User, usersNumber: number) => {
for (let i = 1; i < usersNumber+1: i++) {
user.name = `User ${userNumber}`
cy.request({
method: 'POST',
url: '/createUserEndpoint',
body: user,
headers: {
authorization: 'token'
}
}).then(response => {
return response.body;
});
}
});
And in the test I would like to have:
import { userData } from '../../fixtures'
let user: User = JSON.parse(JSON.stringify(userData));
it('test', () => {
cy.createUsers(user, 3);
)};
But this code doesn't work the way I would expect it to. Cypress sends a request with the same data of the last iteration so with Body:
{...,"name":"User 3",...}
Is it possible to implement one cystom command which would chain multiple commands on each other for a given number? How to do it?bland-salesclerk-62828
02/02/2023, 9:58 PMcy.request({
method: 'POST',
url: '/createUserEndpoint',
body: { ...user, name: `User ${userNumber}`},
headers: {
authorization: 'token'
}
I'm guessing setting body to user is passing by ref, and due to Cypress's command queueing system, all of them are going to read user to whatever value you set last. Instead you should try to clone user and pass it into body, so that each request is reading from its own unique user object instance.best-lunch-5240
02/02/2023, 10:01 PMbland-salesclerk-62828
02/02/2023, 10:01 PMbest-lunch-5240
02/02/2023, 10:09 PMbland-salesclerk-62828
02/02/2023, 10:09 PMbland-salesclerk-62828
02/02/2023, 10:09 PM