• Home
  • Public Speaking
  • Travel
When I first start using Cypress, I was frequently getting errors with "undefined" values after calling a function. The function was returning before the previous assignment was completed. Later, I realized it was due to asynchronous working way. It means, basically all the commands are queued and called sequentially. There is still no issues. However whenever we mix sync and async code, then we start to mix the execution order. In Playwright there is a trivial way to ensure the completion of a call with 'await' keyword. But in Cypess, it is a bit different. Let's see how it works.

1. Sync and Async Code together



In this simple code, what I want to see is:
1
2
wait 3 secs
3
4
test passes.

But what I has is, I already get the 3 & 4 logs before waiting for 3 seconds. Which means cy.wait(3000) was not waited to be completed before moving to next call.


2. 'Then'



This time what we do is, ensuring that wait is completed before moving to log3. What I see in the console is:
1
2
4
wait 3 secs
3
test passes.

So, log3 is waiting for the previous call, but log4 is still running before them.


3. Promises



In Cypress, we can create 'Promises' which promise to return properly. When I execute the above code, what I see is:
1
2
4
test passes
wait 3 secs
3

Even the test finished before wait and log3. Seems like I could not wait for promise properly.


4. Tasks



Instead of calling the promise function, we can just start it as a 'task'. For this purpose, we have to register this task name in the plugins file.


5. 'Wrap'



If I wait for promise to be resolved, I see test passes after the promise:
1
2
4
wait 3 secs
3
test passes.

It is basically same with the second section: connecting log3 and wait with 'then'.


6. 'Wrap' and 'Then'



If I continue to next calls after the promise is resolved, finally I get what I want:
1
2
wait 3 secs
3
4
test passes.