How To Reuse Yielded Value Later In The Test
Solution 1:
Cypress commands are pushed (enqueued) into a queue (called the Command queue --- which is basically an array), and then executed serially (one after another), and asynchronously.
While your cy.log()
will be executed asynchronously, too, after the previous command, the value you pass to it (page1value
) is passed/evaluated synchronously, at the time you push the command to the queue (which is evaluated at the time the callback passed to it()
is called --- at the beginning of the test).
This is just regular JavaScript behavior, and has nothing to do with Cypress. All the commands cy.*
are just methods (functions) on the cy
object, and they're called immediately. What is not called (executed) immediately, is the logic that each command does (e.g. query the DOM for the selector you supply to cy.get()
, log to Command log when you call cy.log('string')
, etc.).
Thus, in your 2nd example:
- You declare
page1value
. - You then immediately enqueue commands
cy.get()
,cy.invoke
,cy.then()
. - And you also immediately enqueue
cy.log
, to which you passpage1value
(which at this time is stillundefined
). - After all commands are enqueued, they start to execute, from top to bottom. When the
cy.then
command takes turn to execute, thepage1value
variable is assigned, but it's no longer used (read) anywhere for the rest of the test (recall that you've already read it when you passed it to thecy.log
command in the previous step).
Thus, what you want to do instead, is:
cy.get('#selector').invoke('text').then(text => {
cy.log(text);
});
In your 3rd example, if you alias something, you need to access that value using another command (remember, everything is asynchronous, so you can't access values that are set asynchronously, in a synchronous manner as you're doing), in this case cy.get('@aliasName')
:
cy.get('#selector').invoke('text').as('page1value');
cy.get('@page1value').then( value => {
cy.log(value);
});
Note that the above explanations are slightly inaccurate and inexhaustive (there are more things going on behind the scenes), for the sake of simplicity. But as an intro to how things work, they should do.
Anyway, you should definitely read Introduction to Cypress.
You may also take a look at my older answers that touch on related concepts:
Post a Comment for "How To Reuse Yielded Value Later In The Test"