Search code examples
javascriptcypressauto-increment

How do I increment automatically a variable when calling a Cypress method?


createUserPatch is an API custom command to create a new User.

You can see that I have created a variable "A" inside it.

The variable is used in the body emails part [a]+'freddie.doe@example.com','type': 'work','primary': true}]

I want to find a way to automatically increase the variable "A" whenever I call the command createUserPatch.

Cypress.Commands.add('createUserPatch', (user) => {
    var A = 1;
    cy.request({
        method: 'POST',
        url:  '/scim/v2/users',
        qs: {
            key : Cypress.env('apiKey')                         
        }, 
        body :{
            schemas: user.schemas,
            userName: user.userName,
            emails: [{ 'value': [A]+'freddie.doe@example.com','type': 'work','primary': true}],
            name : 'Maurice'
        }   
    }).then(res => {
        return res.body;
    });        
});

I use this command in the test below in a before each.

let user = {
    schemas:'["urn:ietf:params:scim:schemas:core:2.0:User"]',
    userName: 'John',
    userId: null,
    groupID: null 
};

describe('Deactivating a user ', () => {

    beforeEach(() => {        
        
        cy.createUserPatch(user).then((newUser) => {
            return user.userId = newUser.id;
        });
    });
....

Each time I run this test. I want the value of the email to be increased.

First test -> 0freddie.doe@example.com

Second test -> 1freddie.doe@example.com

Third test -> 2freddie.doe@example.com

etc...


Solution

  • Cypress clears variables between tests, but a few ways to preserve data have been suggested in other questions (e.g write data to file).

    Since you already use Cypress.env(name) to access environment variables you could use Cypress.env(name, value) to track the prefix.

    Cypress.Commands.add('createUserPatch', (user) => {
    
      let prefix = Cypress.env('emailprefix') || 0;  // first time it may be undefined
                                                     // so "|| 0" initializes it
      Cypress.env('emailprefix', ++prefix);          // increment and save 
    
      cy.request({
        ...
        emails: [{ 'value': prefix+'freddie.doe@example.com','type': 'work','primary': true}],
    

    Note, the prefix value will be preserved between runs, which may or may not be what you want.

    To clear it between runs, add a before() which resets the value

    before(() => Cypress.env('emailprefix', 0) );
    
    beforeEach(() => {
      cy.createUserPatch().then(console.log)
    })