Cypress: Storing Values Into A Variable Synchronously

 


Hello People,

As I have moved towards a new venture in my career, with which I have got opportunity to work with a great and an amazing tool named Cypress.IO. With my previous experience all being into Selenium and JAVA, it was challenging to learn and quickly get into the shoe with Cypress. In my journey of leaning, I got many difficulties as a beginner in Cypress, which I would like to share with all of you. So that it is easier for the people to quickly look and learn from it.

So as we all know JavaScript is asynchronous due to its single-threaded programming feature. Thus it becomes very cumbersome to store the variable value taken out from any calculation or on-screen UI element to be used further for any verification purpose. It would always give a undefined value. Like in the below given example:


Simply I visited a site and fetched an attribute using class, invoked its text and saved it into a variable named var1. Now as required, I printed the value of the variable.


Now, let us see what happens while the execution. 





As we see the cypress logs the statement was printed and variable was undefined. Though the invoke() method worked perfectly and  has yielded the value as "Tutorials Library", but the same did not pass into the variable due to the async behavior of  JavaScript. Read more about the Async behavior of JavaScript, here. 

Therefore, I have identified methods using which I can derive the value into a variables in a synchronous manner and use it ahead in the scope of declaration.

Starting with the first way of doing :

1. cy.wrap()



Find the required element and invoke the attribute or text into a then(). It is moulded such way that it carries the last callback function and carries forward it with promise. Within the scope of then(), wrap() the value after proper manipulation/calculation as a alias variable to the actual value. 

Now wherever required ahead in the code, you can get the alias variable using the cy.get('@varName') and passing it into resoling promise by then(), inside the scope use it anyway required for verification/manipulation.


2. invoke('text').as()



Declare a variable before hand to store the value required. Get the element using a unique CSS/Xpath and perform the .invoke('text') and save it in a alias using the .as('aliasName'). Now wherever required cy.get() the aliasName using an @ operator and resolve promise and use as required. This way you can simply store the text values on UI and use/verify it in the flow in test case.  

That's all for today, would soon come up with such easy but logical series of quick methods to ease our efforts in Cypress.

Thank You !!! 

Comments

Post a Comment

Popular posts from this blog

Passing Data From the TestNG.xml file to Tests

Demo Click Jack Maropost.Com