API Testing
Test HTTP APIs directly with cy.request and intercept for contract validation.
cy.request
cy.request performs HTTP from Node network stack bypassing CORS—ideal for API contract tests alongside UI. Supports method, headers, body, auth, and form data.
Assertions on response.status, response.body, and response.headers validate API behavior without browser rendering.
cy.request({
method: "POST",
url: "/api/users",
body: { email: "ada@example.com", name: "Ada" },
headers: { Authorization: "Bearer " + token },
}).then((response) => {
expect(response.status).to.eq(201);
expect(response.body).to.have.property("id");
});Auth and Session
Obtain token via cy.request login then set cookie or header for subsequent UI tests. cy.session caches authenticated state across specs.
Store test credentials in Cypress env—not hardcoded in repo. cypress.env.json gitignored locally; CI injects secrets.
cy.request("POST", "/api/login", { email, password }).then(({ body }) => {
window.localStorage.setItem("token", body.token);
});Combining API and UI Tests
Seed data with API in beforeEach, assert UI displays seeded data. After UI action, cy.wait("@alias") validates request payload and response.
Hybrid tests faster than pure UI setup and more user-realistic than pure API tests alone.
cy.intercept("DELETE", "/api/items/*").as("deleteItem");
cy.get('[data-cy="delete"]').click();
cy.wait("@deleteItem").its("response.statusCode").should("eq", 204);Contract Testing
Validate response body against JSON schema with ajv in cy.then. Fail when API breaks contract before UI tests mysteriously fail.
Run API-only spec suite on backend deploy pipeline gate before E2E runs.
- Version schemas alongside API OpenAPI spec
- Test error responses 400, 401, 403, 404 explicitly
- Use unique test resources to allow parallel CI workers
import Ajv from "ajv";
const ajv = new Ajv();
cy.request("/api/user/1").then(({ body }) => {
const valid = ajv.validate(userSchema, body);
expect(valid, ajv.errorsText()).to.be.true;
});Limitations
cy.request does not test browser fetch middleware, CORS in browser, or Service Worker interception. Supplement with E2E for those layers.
Rate limiting and WAF may block CI IP ranges—whitelist or use dedicated test environment.
- Do not load-test production with Cypress request loop
- Log request id header in failures for server correlation
- Clean up created resources in afterEach via DELETE request