✅ Quick Tip: Cypress._.repeat
Most days, with words and with code, you don’t want to repeat yourself. You want your code to be DRY and your tests fast.
Recently, I needed to check a large set of text against the character count in a field. In conjunction with Cypress and Faker, I can do that. But, the text set I needed was a lot. And, my normal practice of cy.get("[data-testid='text-field']").type(message);
wasn’t going to cut it.
TL;DR
Use Cypress._.repeat
to create extensive text in a text field
const message = faker.lorem.sentence(6);
const text = Cypress._.repeat(message, 20);
cy.get("[data-testid='text-field']").type(text, { delay: 0 });
So, what’s happening here?
Let’s start from the beginning.
We know we can type using Faker and Cypress. As more text is added with Faker, the longer a test takes. I needed about 120 words to add in a text field. Using Cypress and Faker, this would take about, oh, say…
18 seconds of test time.
Not good.
Looking for solutions, I came across Gleb Bahmutov’s recipe for creating long text. While I’d seen Cypress’ use of Lodash, I didn’t understand its use. His example provided context and gave insight for writing my test.
And, what is Lodash? Well, I found an excellent answer on Reddit.
Okay! I added Cypress._.repeat
and still found myself with a bit of a problem.
The test was still so slow! I needed more.
Cypress offers a delay option when typing and as Sam Lawrence points out, this action is less like a user type and more like a copy and paste. But, once added…
it was enough. Yes. Nine seconds is a lot for one test. But this test is far faster than if I was manually testing it.
Do you see ways I could improve this? What’s your experience with Cypress._.repeat? Would love to hear about your experience!
Till next time…
Written with Enchanted Forest Ambience | 432Hz + 528Hz + 963Hz - Miracle Tone playing in the background