← Back to libraryQuestion 177 of 468
🌲CypressIntermediate

cy.request — API Testing and Test Setup

📌 Definition:

cy.request makes real HTTP requests directly (bypassing the browser/UI). It is used for API testing and, importantly, for fast test setup/teardown — seeding data or logging in via the API instead of the UI.

📖 Detailed Explanation:

Unlike cy.intercept (which controls the browser's requests), cy.request sends an actual request from the test and yields the real response for assertions on status, body, and headers. Its biggest practical use is programmatic setup: instead of clicking through a signup form before every test, POST to /api/register or /api/login to create state in milliseconds, then test the specific feature. This makes suites faster and less flaky. cy.request follows redirects and handles cookies by default, and can send auth tokens/headers for authenticated calls.

🔑 Key Points:
  • Sends REAL HTTP requests; yields response for assertions
  • Ideal for fast setup/teardown (seed data, API login)
  • Bypasses the UI — no rendering/clicking overhead
  • Different from cy.intercept, which stubs the browser's requests
🌍 Real-World Example:

Instead of filling the login form in beforeEach, the team does cy.request('POST', '/api/login', creds).then(res => window.localStorage.setItem('token', res.body.token)); cutting minutes off the suite and removing login-page flakiness.

🎯 Scenario-Based Interview Question:

Every test logs in through the UI, making the suite slow and brittle. What's the idiomatic Cypress fix?