soccerway
soccerway

Reputation: 11991

In a Cypress test, increment function doesn't work which needs to increments the number each time?

In a Cypress test.

I am calling a simple increment function getNumber() which needs to increment the number each time when the function is called.

This number is required to attach to the name of the text field while creating a form i.e. unique form name.

While running the test, it actually returns 1, but running the second time, it still returns 1 instead of 2.

How can I achieve this or is there any better way of doing this?

Someone, please advise a better way of achieving this?

Code:

const getNumber = (() => {
      var count = 0;
      return () => ++count;
    })();
  cy.wrap({ number: getNumber }).invoke('number')
           .then(number => {
               const someNum = number;
               cy.log(someNum);              
              cy.visit("https://sometestsite.com/createForm")
             cy.get('#SomeIdOfTextField').type('Form_Name'+someNum)
        })

Upvotes: 0

Views: 2070

Answers (1)

Brendan
Brendan

Reputation: 4649

You are redeclaring count every time you call getNumber(). Move the count declaration outside of the function like this:

var count = 0;
const getNumber = (() => {
      return () => ++count;
    })();
  cy.wrap({ number: getNumber }).invoke('number')
           .then(number => {
               const someNum = number;
               cy.log(someNum);              
              cy.visit("https://sometestsite.com/createForm")
             cy.get('#SomeIdOfTextField').type('Form_Name'+someNum)
        })

Upvotes: 2

Related Questions