Understanding How Cypress Works
Let's understand how Cypress works in this lesson.
We'll cover the following...
Although the Cypress test seems simple, Cypress is a tool where the apparent simplicity of the developer commands hides a fair amount of complexity behind the scenes. In order to effectively write tests in Cypress, it is important to take a step back to understand how Cypress works to avoid a lot of confusion later on. Cypress’ asynchronous structure means that a lot of common JavaScript patterns either won’t work or aren’t recommended in Cypress. For example, using regular variable assignment is going to cause you trouble.
The most important thing to understand about Cypress is that although Cypress commands appear to be regular JavaScript function calls, in fact, all Cypress commands are asynchronous. In effect, each time you use the cy
command, you are creating something like a JavaScript promise, and subsequent cy
commands are in the then
clause of the preceding command, meaning that each successive cy
command only executes after the previous one has completed.
When the Cypress command is actually run as part of the test, it queues itself a list of commands in the test and returns immediately. What we think of as the actual command—the get
or click
or whatever—only executes as part of this queue of promises once the entire test has loaded.
The most important implication of this behavior is that Cypress is a world unto itself. Normal JavaScript assignment or logic that is not mediated through Cypress does not see Cypress stuff at all, and conversely, everything you do in a Cypress test needs to go through the cy
command. Cypress has constructs to allow you to do things like variable assignment and logic inside Cypress-land, but if you write normal variable assignments with let
or const
, those assignments will happen as the test loads. They will not be able to see Cypress data, and Cypress ...