Luke
Luke

Reputation: 47

can we use cypress wait without then block?

https://docs.cypress.io/api/commands/wait - cy.wait() is used to wait for an arbitrary number of milliseconds.

What's the difference in the following two snippets

// snippet-1

cy.wait(10*1000);
// other code
// snippet - 2
cy.wait(10*1000).then(()=>{
// other code
})

I tried to run the following code to test how it is working and i got the output mentioned in the below image.

cy.wait(10 * 1000).then(() =>
  cy.log("This is inside wait()" + new Date().toLocaleTimeString())
);
cy.log("This is after wait()" + new Date().toLocaleTimeString());

These are the log results:

enter image description here

From the above image, it looks like we should add our code inside .then because that will be executed after cy.wait . I also have seen people writing their test cases just like snippet-1

Which one is correct and which one we should use?

Upvotes: 1

Views: 486

Answers (2)

Mads Brugger
Mads Brugger

Reputation: 250

If you want a better log, use a custom command to make a version that defers evaluating the value.

By providing a callback, the new Date().toLocaleTimeString() expression evaluates when you expect it to.

Cypress.Commands.add('logLazy', (thingToLog) => {
  if (typeof thingToLog === 'function') {
    cy.log(thingToLog())
  } else {
    cy.log(thingToLog)
  }
})

cy.wait(3_000).then(() =>
  cy.log("This is inside wait()" + new Date().toLocaleTimeString())
);
cy.log("This is after wait()" + new Date().toLocaleTimeString());

cy.wait(3_000).then(() =>
  cy.logLazy("This is LAZY LOG inside wait()" + new Date().toLocaleTimeString())
);
cy.logLazy(() => "This is LAZY LOG after wait()" + new Date().toLocaleTimeString());

enter image description here

Upvotes: 3

agoff
agoff

Reputation: 7125

Cypress commands use the current value of variables and resolve function values when enqueuing commands. So, in your example, the commands are enqueued as .wait() and then the outer .log(). The value of the date string is calculated when the command is enqueued. The inner .log() is enqueued within the .then(), and thus has a later date string.

Either snippet is fine to use, but be aware of how the subsequent commands in your test will react. Are you manipulating some variable during your .wait(), and you would not want the original value to be used for your Cypress command? Probably a good idea to place that command within a .then() or some other Cypress command. Are you just interacting with the website and need to wait 10 seconds? You probably don't need to worry about placing commands inside .then().

Upvotes: -1

Related Questions