How to Test API Status Code in Cypress: Simple Guide
To test an API status code in Cypress, use
cy.request() to send the API call and then assert the response.status with expect(). This verifies the server returns the expected HTTP status like 200 or 404.Syntax
The basic syntax to test an API status code in Cypress involves using cy.request() to make the HTTP request, then chaining a .then() callback to access the response object. Inside the callback, use expect(response.status) to assert the status code.
cy.request(url): Sends an HTTP request to the given URL..then(response => { ... }): Handles the response object.expect(response.status).to.eq(expectedStatus): Checks if the status code matches the expected value.
javascript
cy.request('https://example.com/api').then((response) => { expect(response.status).to.eq(200) })
Example
This example shows how to test that a GET request to a public API returns a 200 status code, indicating success.
javascript
describe('API Status Code Test', () => { it('should return status 200 for GET request', () => { cy.request('https://jsonplaceholder.typicode.com/posts/1') .then((response) => { expect(response.status).to.eq(200) }) }) })
Output
Test passes if the API returns status 200; fails otherwise.
Common Pitfalls
Common mistakes when testing API status codes in Cypress include:
- Not using
cy.request()and trying to test API calls through UI commands. - Forgetting to assert the
response.statusand only checking the body. - Not handling asynchronous behavior properly, causing tests to pass or fail incorrectly.
Always use cy.request() for direct API testing and assert the status explicitly.
javascript
/* Wrong way: No status assertion */ cy.request('https://jsonplaceholder.typicode.com/posts/1').then((response) => { // Missing status check expect(response.body).to.have.property('id') }) /* Right way: Assert status code */ cy.request('https://jsonplaceholder.typicode.com/posts/1').then((response) => { expect(response.status).to.eq(200) expect(response.body).to.have.property('id') })
Quick Reference
| Command | Description |
|---|---|
| cy.request(url) | Sends an HTTP request to the specified URL |
| response.status | Contains the HTTP status code from the response |
| expect(response.status).to.eq(code) | Asserts the status code equals the expected code |
| cy.request(method, url) | Sends a request with a specific HTTP method (GET, POST, etc.) |
Key Takeaways
Use cy.request() to send API calls directly in Cypress tests.
Always assert response.status to verify the API status code.
Handle asynchronous responses with .then() to access the response object.
Avoid testing API status codes through UI interactions; test APIs directly.
Check both status code and response body for thorough API testing.