These are some of the best practices from the official Cypress documentation which are actually anti-patterns.
I'll explain why and give you better alternatives.
1. Use data-*
attributes
Why it's bad
data-*
attributes clutter your production code and make your tests be dependent on implementation details.
Better alternative: Cypress Testing Library
It doesn't require you to add extra stuff to your markup, makes your tests more abstract, and helps you improve accessibility.
Pro tips
1. Use ESLint to forbid cy.get()
entirely
{
"rules": {
"no-restricted-properties": [
"error",
{
"object": "cy",
"property": "get",
"message": "Use Testing Library query."
}
]
}
}
2. Follow Testing Library priority guide when writing queries
2. Use route aliases
Why it's bad
It still makes your tests flaky, and it makes them be dependent on implementation details.
Better alternative: UI assertions
Wait for something to appear in the UI, not for network requests to finish.
Bad:
cy.intercept("**/posts").as("publish");
cy.findByRole("button", { name: "Publish" }).click();
cy.wait("@publish");
Good:
cy.findByRole("button", { name: "Publish" }).click();
cy.findByRole("heading", { name: "My new post" }).to("be.visible");
Pro tip
Use ESLint to forbid cy.wait()
entirely
{
"rules": {
"no-restricted-properties": [
"error",
{
"object": "cy",
"property": "wait",
"message": "Use UI assertion."
}
]
}
}
If you liked this article, you should check out
More Cypress Best Practices
Top comments (0)