Sitemap
Can Seker

Can Seker

Senior Software Test Engineer

Cypress: JavaScript API Testing

4 min readMay 11, 2023

API tests are used to check whether APIs are working correctly or not. Such tests can verify whether the API responds to a specific request URL, whether the data returned by the response is correct, and whether the API responds correctly to error situations. Cypress provides a way to perform API tests using the cy.request() command. This command allows you to send HTTP requests and test responses. When performing API tests with Cypress, you can use the same Cypress test interface for writing test code and analyzing results. This enables API tests to be performed quickly and results to be easily viewed.

You can follow the steps below to start writing your tests using JavaScript and Cypress:

# Node.js
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs

# Cypress
npm install cypress

Create a file to write your tests. You can name it something like userTests.cy.js

Write your tests using the describe() and it() functions. The describe() function represents a block of tests that are grouped together, while the it() functions represent individual tests within that block.

describe("GET /v2/user", function() {
it("TC", function () {
// Test Cases
});
it("POST /v2/user/{userName}", function () {
// Test Cases
});
});

In your tests, make API calls using request functions such as GET, POST, PUT, PATCH, or DELETE.

cy.request('GET', 'https://petstore.swagger.io/v2/user/testqauser21')

Check the responses of your requests using the expect() function. For example, you can expect the status code of the response to be 200 (OK):

const userName = 'testqauser21'

cy.request('GET', `https://petstore.swagger.io/v2/user/`+userName)
.then((response) => {
expect(response.status).to.eq(200)
})

HTTP status codes are three-digit numeric codes that indicate how a web server responded to an HTTP request.

  • 200 OK: The request was successfully processed and the expected data was sent by the server in response.
  • 301 Moved Permanently: The requested resource has been permanently moved to a different URL.
  • 400 Bad Request: The server could not understand the request because it was malformed or invalid.
  • 401 Unauthorized: The request was rejected by the server because it requires authentication.
  • 404 Not Found: The requested resource could not be found on the server.
  • 403 Forbidden: The server refused to process the request by the client because the client failed to provide correct authentication or tried to access a forbidden resource.
  • 500 Internal Server Error: The server encountered an error while processing the request.
  • 503 Service Unavailable: The server couldn’t process or respond to the client’s request, usually due to server overload, maintenance work, or temporary service outage.

Cypress allows you to send parameters like request body, header, and query string (qs) while creating HTTP requests.

Get Can Seker’s stories in your inbox

Join Medium for free to get updates from this writer.

As shown in the code example below, you can send request body and headers while creating a POST request:

      const postData = {
"id": 78799781,
"username": "testqauser21",
"firstName": "test",
"lastName": "qa",
"email": "testqa@test.com",
"password": "test123",
"phone": "54545454545",
"userStatus": 1
}
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
}

cy.request({
method: 'POST',
url: 'https://petstore.swagger.io/v2/user',
body: postData,
headers: headers
})
.then((response) => {
expect(response.status).to.eq(200)
})

You can also send Query String (qs) values while creating a request in the same way.

const userName = 'testqauser21'
const qsParams = {
param1: 'test1',
param2: 'test2'
}
cy.request('GET', `https://petstore.swagger.io/v2/user/`+userName, {
query: qsParams
})
.then((response) => {
expect(response.status).to.eq(200)
})

After creating your documentation, you can run the userTests.cy.js file using the following command:

npx cypress run

When the command “npx cypress run” is executed, your tests will run and a report will be displayed as output showing whether the tests have passed or failed.

 Petstore API TESTING
√ POST /v2/user (User Create) (993ms)
√ PUT /v2/user/{username} (User Update) (220ms)
√ GET /v2/user/{userName} (243ms)
√ GET /v2/user/login} (224ms)
√ Delete /v2/user/ (User Delete) (223ms)
1) GET /v2/user/{userName}
√ GET /v2/user/logout (207ms)


6 passing (3s)
1 failing

1) Petstore API TESTING
GET /v2/user/{userName}:
CypressError: `cy.request()` failed on:

https://petstore.swagger.io/v2/user/testqa7451656

The response we received from your web server was:

> 404: Not Found

This was considered a failure because the status code was not `2xx` or `3xx`.

If you do not want status codes to cause failures pass the option: `failOnStatusCode: false`

(Results)

┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Tests: 7 │
│ Passing: 6 │
│ Failing: 1 │
│ Pending: 0 │
│ Skipped: 0 │
│ Screenshots: 1 │
│ Video: true │
│ Duration: 2 seconds │
│ Spec Ran: UserTests.cy.js │
└────────────────────────────────────────────────────────────────────────────────────────────────┘


(Screenshots)

- cypress-api-testing\cypress\screenshots\ (1280x720)
UserTests.cy.js\Petstore API TESTING -- GET v2user{userName} (failed).png


(Video)

- Started processing: Compressing to 32 CRF
- Finished processing: 0 seconds

- Video output: cypress-api-testing\cypress\videos\UserTests.cy.js.mp4


====================================================================================================

(Run Finished)


Spec Tests Passing Failing Pending Skipped
┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│ × UserTests.cy.js 00:02 7 6 1 - - │
└────────────────────────────────────────────────────────────────────────────────────────────────┘
× 1 of 1 failed (100%) 00:02 7 6 1 - -

This output shows whether the tests have passed or failed, and displays error messages for the failed tests.

npx cypress open

When you execute the command “npx cypress open”, you will be able to run your tests and a dashboard will be displayed as output showing whether the tests have passed or failed.

Press enter or click to view image in full size

You can find more information about Cypress at the following link.

You can access the demo project I have prepared for you from the repository link.

About to be together in our next article.

Stay Tuned

--

--

Can Seker
Can Seker

Written by Can Seker

Senior Software Test Engineer