DEV Community

Evgeny Orekhov
Evgeny Orekhov

Posted on • Updated on

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

Top comments (0)