'How to force fail a test in Cypress.io

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?



Solution 1:[1]

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')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zach Bloomquist