cypressflakyness

Before assertion is not running


I'm encountering an unusual issue. The first time I execute the code in the browser, it progresses halfway but encounters an error during the afterEach assertion.

Interestingly, when I rerun the same code, an error emerges during the before assertion. Regrettably, I'm struggling to pinpoint the root cause of this problem and comprehend the underlying reasons for its occurrence.

/// <reference types="cypress"/>

describe("Validate login functionality", () => {
  //before
  before(function () {
    cy.visit("https://www.saucedemo.com/");
  });
  //beforeEach
  beforeEach(function () {
    cy.get("#user-name").type("standard_user");
    cy.get("#password").type("secret_sauce");
    cy.get("#login-button").click();
  });

  //Test1
  it("Validate link", () => {
    cy.get(
      "a[id='item_4_title_link'] div[class='inventory_item_name']"
    ).click();
  });

  //Test2
  it("Validate Add to cart", () => {
    cy.get("#add-to-cart-sauce-labs-backpack").click();
  });

  afterEach(function () {
    cy.get("#react-burger-menu-btn").click();
    cy.get("#logout_sidebar_link").click();
  });
});

I've made several attempts to execute the identical code on various browsers, and every time the issue persists. Despite thoroughly reviewing the code multiple times, I find myself unable to identify the source of the problem.

Kindly pinpoint the issue in code. I am using latest version of Cypress 13.0


Solution

  • Testing the saucedemo.com site has come up previously, and there is some unknown factor that makes it difficult for Cypress to handle.

    A couple of modifications make the test stable

    To ensure the test isn't flaky I added @cypress/grep to enable burn-testing.

    import registerCypressGrep from '@cypress/grep/src/support'
    Cypress.env('burn', 10)
    registerCypressGrep()
    
    describe("Validate login functionality", () => {
      beforeEach(function () {
        cy.visit("https://www.saucedemo.com/")
        cy.get("#user-name").type("standard_user");
        cy.get("#password").type("secret_sauce");
        cy.get("#login-button").click();
      });
    
      it("Validate link", () => {
        cy.get(
          "a[id='item_4_title_link'] div[class='inventory_item_name']"
        ).click();
      });
    
      it("Validate Add to cart", () => {
        cy.get("#add-to-cart-sauce-labs-backpack").click();
      });
    
      afterEach(function () {
        cy.get("#react-burger-menu-btn").click();
        cy.get("#logout_sidebar_link").click();
      });
    })
    

    enter image description here