Skip to main content

Cypress Closures

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
Submitted by arilio666 on December 7, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.


At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.