40

In Cypress.io is there a way that I can force a test to fail if a certain condition is met?

For example, on my webpage, if the string "Sorry, something went wrong." is present on the page I want the test to fail. Currently here is what I am doing.

/// <reference types="Cypress" />

describe("These tests are designed to fail if certain criteria are met.", () => {
  beforeEach(() => {
    cy.visit("");
  });

  specify("If 'Sorry, something went wrong.' is present on page, FAIL ", () => {
    cy.contains("Sorry, something went wrong.");
  });
});

Right now, if "Sorry, something went wrong." is found, the test succeeds. How do I fail the test if this condition is met?

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Christian Gentry
  • 811
  • 3
  • 10
  • 15
  • Does this answer your question? [Cypress: Test if element does not exist](https://stackoverflow.com/questions/48915773/cypress-test-if-element-does-not-exist) – M. Justin Dec 09 '21 at 23:31

1 Answers1

65

You can just throw a JavaScript Exception to fail the test:

throw new Error("test fails here")

However, in your situation, I would recommend using the .should('not.exist') assertion instead:

cy.contains("Sorry, something went wrong").should('not.exist')
Zach Bloomquist
  • 5,309
  • 29
  • 44
  • 2
    So the question is how to force a test to fail *if a certain condition is met*. This answers a different question from the one that was asked. Furthermore, recommending an alternative approach is generally contraindicated because while it might help the original poster, it is not useful for the majority of readers who are looking for a solution to the conditional failure assertion question - for them, `should()` is possibly irrelevant (for example, a javascript test that is not covered by the options in `should()`, or if a custom assertion message is desired). – Peter Kionga-Kamau Apr 26 '21 at 17:52
  • 2
    The question was "Right now, if "Sorry, something went wrong." is found, the test succeeds. How do I fail the test if this condition is met?" :) – Zach Bloomquist Apr 26 '21 at 22:18
  • If you would like to conditionally fail the test, you can use a javascript `if` statement, either inside of a `cy.then` or synchronously. – Zach Bloomquist Apr 26 '21 at 22:18
  • 1
    Right, I'm not saying you have not helped the OP - my point was that others will be looking for a conditional manual assertion and they find this post, so it's still somewhat somewhat useful to perhaps include a conditional example. – Peter Kionga-Kamau Apr 27 '21 at 12:53
  • Is there a way to force-fail "immediately" in a `should(cb)` callback? Because if I throw in there, it just keeps retrying until it hits the timeout. – Attila Szeremi Feb 02 '22 at 15:23