DEV Community

Evgeny Orekhov
Evgeny Orekhov

Posted on • Edited on

1

Cypress Best Practices that are actually bad

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."
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

Good:

cy.findByRole("button", { name: "Publish" }).click();
cy.findByRole("heading", { name: "My new post" }).to("be.visible");
Enter fullscreen mode Exit fullscreen mode

Pro tip

Use ESLint to forbid cy.wait() entirely

{
  "rules": {
    "no-restricted-properties": [
      "error",
      {
        "object": "cy",
        "property": "wait",
        "message": "Use UI assertion."
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

If you liked this article, you should check out
More Cypress Best Practices

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay