Cypress is the JavaScript end-to-end testing framework with time-travel debugging, automatic waiting, and a beautiful test runner.
Write Your First Test
describe("Product Search", () => {
beforeEach(() => {
cy.visit("/products");
});
it("searches for products", () => {
cy.get('[data-testid="search-input"]').type("widget");
cy.get('[data-testid="search-button"]').click();
cy.get('[data-testid="product-card"]').should("have.length.greaterThan", 0);
cy.contains("Widget Pro").should("be.visible");
});
it("filters by price", () => {
cy.get('[data-testid="max-price"]').clear().type("50");
cy.get('[data-testid="apply-filter"]').click();
cy.get('[data-testid="product-price"]').each(($el) => {
const price = parseFloat($el.text().replace("$", ""));
expect(price).to.be.lessThan(50);
});
});
});
Network Interception
it("handles API errors gracefully", () => {
cy.intercept("GET", "/api/products", { statusCode: 500, body: { error: "Server Error" } }).as("getProducts");
cy.visit("/products");
cy.wait("@getProducts");
cy.contains("Something went wrong").should("be.visible");
cy.get('[data-testid="retry-button"]').should("be.visible");
});
it("mocks API data", () => {
cy.intercept("GET", "/api/products", { fixture: "products.json" }).as("getProducts");
cy.visit("/products");
cy.wait("@getProducts");
cy.get('[data-testid="product-card"]').should("have.length", 3);
});
it("waits for slow API", () => {
cy.intercept("GET", "/api/products", (req) => {
req.reply({ delay: 2000, body: [] });
});
cy.visit("/products");
cy.get('[data-testid="loading-spinner"]').should("be.visible");
cy.get('[data-testid="loading-spinner"]').should("not.exist");
});
Custom Commands
// cypress/support/commands.ts
Cypress.Commands.add("login", (email: string, password: string) => {
cy.session([email, password], () => {
cy.visit("/login");
cy.get("#email").type(email);
cy.get("#password").type(password);
cy.get("button[type=submit]").click();
cy.url().should("include", "/dashboard");
});
});
// Usage
it("shows dashboard for logged in user", () => {
cy.login("test@example.com", "password123");
cy.visit("/dashboard");
cy.contains("Welcome").should("be.visible");
});
Component Testing
import ProductCard from "./ProductCard";
it("renders product info", () => {
cy.mount(<ProductCard product={{ title: "Widget", price: 29.99, image: "/widget.jpg" }} />);
cy.contains("Widget").should("be.visible");
cy.contains("$29.99").should("be.visible");
cy.get("img").should("have.attr", "src", "/widget.jpg");
});
it("calls onAddToCart", () => {
const onAdd = cy.spy().as("addSpy");
cy.mount(<ProductCard product={product} onAddToCart={onAdd} />);
cy.get('[data-testid="add-to-cart"]').click();
cy.get("@addSpy").should("have.been.calledOnce");
});
Test your scraping integrations? My Apify tools + Cypress = reliable data pipelines.
Custom testing solution? Email spinov001@gmail.com
Top comments (0)