0
0
CypressHow-ToBeginner ยท 4 min read

How to Use cy.request in Cypress for API Testing

Use cy.request in Cypress to send HTTP requests like GET, POST, PUT, or DELETE directly from your tests without visiting a page. It helps test APIs by making requests and asserting responses easily with simple syntax.
๐Ÿ“

Syntax

The cy.request command sends an HTTP request. You can specify the method, URL, headers, body, and other options.

Basic syntax:

  • method: HTTP method like GET, POST, PUT, DELETE (default is GET)
  • url: The endpoint URL to request
  • body: Data to send with POST or PUT requests
  • headers: Optional HTTP headers
  • failOnStatusCode: Set to false to prevent test failure on error status codes
javascript
cy.request({
  method: 'GET',
  url: '/api/users',
  headers: { 'Authorization': 'Bearer token' },
  failOnStatusCode: false
}).then((response) => {
  // assertions here
})
๐Ÿ’ป

Example

This example shows how to send a POST request to create a user and check the response status and body.

javascript
describe('API Test with cy.request', () => {
  it('creates a new user and verifies response', () => {
    cy.request({
      method: 'POST',
      url: 'https://jsonplaceholder.typicode.com/users',
      body: {
        name: 'John Doe',
        email: 'john@example.com'
      }
    }).then((response) => {
      expect(response.status).to.equal(201)
      expect(response.body).to.have.property('name', 'John Doe')
      expect(response.body).to.have.property('email', 'john@example.com')
    })
  })
})
Output
Test passes if response status is 201 and body contains the sent user data.
โš ๏ธ

Common Pitfalls

Common mistakes when using cy.request include:

  • Not handling asynchronous nature properly by missing then for assertions.
  • Forgetting to set failOnStatusCode: false when testing error responses, causing tests to fail unexpectedly.
  • Using relative URLs without setting baseUrl in Cypress config, leading to request failures.
  • Sending incorrect request body format (e.g., forgetting to stringify JSON if needed).
javascript
/* Wrong: Missing then for assertions */
cy.request('GET', '/api/data')
expect(true).to.be.true // This runs before request finishes

/* Right: Use then to wait for response */
cy.request('GET', '/api/data').then((response) => {
  expect(response.status).to.equal(200)
})
๐Ÿ“Š

Quick Reference

OptionDescriptionDefault
methodHTTP method (GET, POST, etc.)GET
urlRequest URL or pathRequired
bodyData sent with POST/PUT requestsnull
headersHTTP headers object{}
failOnStatusCodeDo not fail test on error statustrue
timeoutRequest timeout in msdefault Cypress timeout
โœ…

Key Takeaways

Use cy.request to send HTTP requests directly in Cypress tests without UI interaction.
Always use .then() to handle the asynchronous response and make assertions.
Set failOnStatusCode to false when testing expected error responses to avoid test failures.
Use full URLs or configure baseUrl in Cypress config for relative paths.
Check response status and body to verify API behavior accurately.