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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →