Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Conditional Testing in Cypress: Best Practices

· 6 min read · Home Tech

In this article
  1. Why Conditional Testing Is Tricky in Cypress
  2. The Core Rule: Prefer Deterministic Tests
  3. When Conditional Testing Is Acceptable
  4. How to Write Conditional Logic Safely
  5. Common Mistakes That Break Tests
  6. Alternatives to Conditional Testing
  7. Best Practices Summary
  8. Frequently Asked Questions

Conditional testing in Cypress—running different assertions or actions based on a runtime condition—is best handled by avoiding it wherever possible, and when unavoidable, by using explicit, deterministic checks like cy.get().then() with a fallback, rather than relying on built-in retry-ability. This article explains why conditional logic breaks Cypress's core model, provides concrete patterns for the few scenarios where it's legitimate (like handling A/B tests or transient UI states), and outlines best practices to keep your tests reliable and maintainable.

Why Conditional Testing Is Tricky in Cypress

Cypress commands are not like traditional DOM queries—they automatically retry until an assertion passes or a timeout expires. This built-in retry is what makes tests stable, but it fights against conditional logic. If you write if (cy.get('.banner').exists()), the command doesn't return a boolean; it either passes (and continues) or fails (and the test stops). There's no straightforward "try this, and if it's not there, do that" because the retry mechanism doesn't know how to "give up" gracefully. This is why many Cypress users hit the infamous "Timed out retrying" error when attempting naive conditionals.

The Core Rule: Prefer Deterministic Tests

The best practice is to design your application and tests so that conditional logic isn't needed. This means controlling the state of the app before each test. For example, if a welcome modal appears only on first visit, you can clear localStorage or set a flag before the test runs. If a feature is behind a feature flag, you can set that flag via a backend API call or a custom Cypress command. By making the app's state deterministic, you eliminate the need for conditionals in your test code, which makes tests faster, more readable, and less flaky.

When Conditional Testing Is Acceptable

There are a few real-world scenarios where you can't avoid a conditional check:

  • A/B testing where your app shows different variants to different users, and you need to assert on whichever variant is shown.
  • Transient UI states like loading spinners or toast notifications that may or may not appear before an assertion.
  • Third-party embeds (e.g., cookie consent banners) that may or may not load depending on external factors.

In these cases, the conditional must be handled carefully, but it's still a last resort. Before adding a conditional, ask yourself: can I force the state? Can I stub the API? Can I assert on a higher-level invariant that doesn't depend on the variant?

How to Write Conditional Logic Safely

When you must use a conditional, the recommended pattern is to use cy.get() with a then() callback and a timeout that is short enough to fail fast, combined with a fallback. Here's a concrete example:

  1. Use cy.get('selector', { timeout: 1000 }).then(($el) => { ... }) to attempt to find the element.
  2. In the then() callback, check if the element exists using Cypress.$ or by checking $el.length.
  3. If it exists, perform the desired action; if not, skip it.
cy.get('.cookie-banner', { timeout: 1000 }).then(($banner) => {
  if ($banner.length) {
    cy.wrap($banner).find('button').click();
  }
});

Note: This pattern still relies on Cypress's retry for the initial cy.get(), but the timeout is short so it fails quickly if the element is truly absent. Then the then() callback runs once, allowing you to branch. This is the official recommended approach for handling elements that may or may not exist.

Common Mistakes That Break Tests

  • Using cy.exists() or cy.isVisible() directly—these are not real Cypress commands and will throw errors.
  • Using cy.get() inside an if statement—the command will always run and fail if the element is absent, regardless of the condition.
  • Not setting a short timeout—the default 4-second timeout makes tests slow when the element is absent.
  • Mixing async and sync code—Cypress commands are asynchronous; you can't use them in a synchronous if without wrapping in then().

A common misconception is that cy.get().should('exist') can be used as a boolean. It can't—it either passes or fails the test. The only way to get a boolean is to use the then() callback and inspect the jQuery object.

Alternatives to Conditional Testing

Before resorting to conditionals, consider these alternatives:

  • Stub network requests—use cy.intercept() to control what the app receives, making the UI deterministic.
  • Set localStorage or cookies—many UI states (like dismissed banners) are stored client-side; set them before the test.
  • Use data attributes—add stable data-testid attributes to elements that are always present, and assert on those instead of conditional elements.
  • Split tests—write separate tests for each variant, and use a test runner option to run only one variant at a time.

These approaches keep tests linear and predictable, which is the core of Cypress's philosophy.

Best Practices Summary

  1. Minimize conditionals—design tests to be deterministic.
  2. If you must use a conditional, use the cy.get().then() pattern with a short timeout.
  3. Never use cy.get() in an if statement directly.
  4. Always provide a fallback action or assertion for the "else" branch.
  5. Document why the conditional is necessary in a comment.
  6. Keep the conditional logic isolated in a custom command (e.g., cy.dismissBannerIfPresent()) to improve readability.

Following these guidelines will make your Cypress tests more reliable, faster, and easier to maintain.

Frequently Asked Questions

Can I use cy.exists() in Cypress?

No, cy.exists() is not a built-in Cypress command. It's a common mistake from other testing frameworks. Cypress's philosophy is that you should know what's on the page; if you don't, you need to handle it with the then() pattern described above.

How do I check if an element is visible before clicking it?

Use cy.get('selector').should('be.visible').click(). If the element may not be visible, you can use the conditional pattern with a short timeout to check visibility: cy.get('selector', { timeout: 1000 }).then(($el) => { if (Cypress.dom.isVisible($el)) { ... } }).

Why does my conditional test time out even when the element is absent?

Because cy.get() retries until the element exists or the timeout expires. If you don't set a short timeout, it waits the default 4 seconds (or your global default) before failing, which makes your test slow and may cause a false failure if the element appears later.

Is conditional testing ever a good idea in Cypress?

Yes, but only in specific scenarios like A/B testing or third-party widgets where you cannot control the app's state. In those cases, use the then() pattern and keep the conditional as small as possible. For most tests, you should aim to make the app state deterministic.

Can I use cy.wait() to avoid conditionals?

Using cy.wait() with a fixed time is an anti-pattern because it slows tests and can still be flaky. It's better to wait for a specific element or network response using cy.get() with an assertion or cy.intercept().

How do I handle a cookie consent banner that appears randomly?

Ideally, stub the banner's API or set a cookie to dismiss it before the test. If that's not possible, use the conditional pattern to click the accept button only if it appears, with a short timeout so it doesn't slow down tests where it's absent.