Cypress Closures

Profile picture for user arilio666

A closure is a combination of functions or commands bundled together (enclosed) with references to its surrounding state.

We all know to access what the cypress command yields, we use the .then() command. Inside then, we use a callback function as the argument. By using callback functions with then(), we create a closure. Closures enable us to keep references around to refer to work done in previous commands. 

We can nest more cypress commands within this then block; Each nested functions or command has access to the work done in previous commands. This structure of command is easy to read and understand. The commands outside or after the then nest will not run unless this nested block command gets executed.

it.only('Verify compare subscription', () => {
    cy.get("button[aria-label='Close'] ").click()

    cy.contains('Compare').then(($compare) => {
    // this command will run after all previous command finished