DEV Community

Cover image for How to run a test multiple times with Cypress to prove it is stable
Walmyr
Walmyr

Posted on • Edited on

How to run a test multiple times with Cypress to prove it is stable

The series "Pinches of Cypress" is getting track!

Today you will learn how to ensure that your tests behave the same way when run multiple times.

Cypress.io is a fantastic testing framework!

It packs together with it several other famous libraries to make life easier for its users, that is, your life!

One of these libraries is lodash.

Just use

Cypress._

And you can invoke any feature of lodash. 🤩

Among the various features of lodash, one that “fits like a glove” for the problem we want to solve is .times.

An example would ease the understanding, right?

Here we go!

Cypress._.times(5, () => {
  it.only("successfully submits the form", () => {
    const customer = {
      firstName: "John",
      lastName: "Doe",
      email: "john-doe@example.com"
    };

    cy.fillMandatoryFields(customer);
    cy.contains("Send").click();

    cy.get(".success p")
      .should("contain", "Form successfully submitted.");
  });
});
Enter fullscreen mode Exit fullscreen mode

After running the above test, I have the following result.

Sample app
  âś“ successfully submits the form (1725ms)
  âś“ successfully submits the form (1212ms)
  âś“ successfully submits the form (1200ms)
  âś“ successfully submits the form (1195ms)
  âś“ successfully submits the form (1256ms)


5 passing (8s)
Enter fullscreen mode Exit fullscreen mode

As you can see, my test looks stable and passed 5 times in a row. Yay! 🎉

Problem solved!


What's up? Any thoughts about the series?

I'm collecting feedback and creating a backlog for the next posts. Leave a comment with what you would like me to address in future content.


This post was originally published in Portuguese on the Talking About Testing blog.


Would you like to learn about test automation with Cypress? Get to know my online courses on Udemy.

Top comments (8)

Collapse
 
jokosanyang profile image
Joko Sanyang

What an elegant solution!

Collapse
 
walmyrlimaesilv profile image
Walmyr

Thanks!

Collapse
 
prasannakumar1 profile image
Prasanna-Kumar-1 • Edited

@walmyrlimaesilv ..thanks for the nice post.

How is it different from 'retries' in cypress?

Collapse
 
walmyrlimaesilv profile image
Walmyr

The idea of using it would be to test that your test is stable, not to retry in case it’s flakey.

Collapse
 
prasannakumar1 profile image
Prasanna-Kumar-1

Got it. Thanks @walmyrlimaesilv

Thread Thread
 
walmyrlimaesilv profile image
Walmyr

You’re welcome!

Collapse
 
danielramos84 profile image
DRamos

Nice and easy, will be using this on my tests. Beats having to manually reload cypress test runner to re-execute a test.

Collapse
 
walmyrlimaesilv profile image
Walmyr

I’m glad you liked it!