Cypress Commands & Assertions

Advanced Cypress commands and assertions.

Assertions

Should
cy.get("button").should("be.visible");
cy.get("button").should("be.disabled");
cy.get("button").should("have.text", "Click");
cy.get("button").should("have.class", "active");

Multiple assertions
cy.get("button")
  .should("be.visible")
  .and("have.text", "Submit");

Waiting

Wait for element
cy.get(".element", { timeout: 10000 });

Wait time
cy.wait(1000);

Wait for request
cy.intercept("GET", "/api/users").as("getUsers");
cy.wait("@getUsers");

Wait for condition
cy.get(".loading").should("not.exist");

Network Requests

Intercept
cy.intercept("GET", "/api/data", {
  statusCode: 200,
  body: { data: "mocked" }
}).as("getData");

Request
cy.request("POST", "/api/login", {
  username: "user",
  password: "pass"
});

Custom Commands

Define in commands.js
Cypress.Commands.add("login", (email, password) => {
  cy.visit("/login");
  cy.get("[data-testid=email]").type(email);
  cy.get("[data-testid=password]").type(password);
  cy.get("[data-testid=submit]").click();
});

Use in test
cy.login("[email protected]", "password123");