4

I'm learning about Cypress.io and came across this statement in their official site Cypress.io

"Cypress commands do not return their subjects, they yield them."

What is the difference between "yield" and "return" in commands in cypress.io?

mjquito
  • 582
  • 1
  • 6
  • 15

2 Answers2

3

I take yield to mean 'pay it forward', whereas return = 'pay it back'.

See Core Concepts

Cypress commands are asynchronous and get queued for execution at a later time. During execution, subjects are yielded from one command to the next, and a lot of helpful Cypress code runs between each command to ensure everything is in order.

1

They do not synchronously return objects like you would expect, it takes a bit of time to get used to - but once you get it, you get it.

This will not work like you expect because cy.get is asynchronous so myButton will not be set before you call .click() on it:

var myButton = cy.get(#myButton);
myButton.click(); //Nope!

Cypress commands yield objects to Chainers which queue up actions to perform, so you would use it like this:

cy.get(#myButton).click(); //Yes!

Or:

cy.get(#myButton).then(myButton => {
  // do stuff with myButton here
});

Some additional reading: https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Return-Values

Brendan
  • 4,327
  • 1
  • 23
  • 33