Using the npm axios for invoking cypress API

 

Recently I faced a challenge of obtaining a value to be passed for a search field. When I discussed with my teammates I was asked to use the npm axios plugin to make an API call for achieving the goal.

For this I will explain how I used the npm axios and installed into my cypress test framework. The challenge was to first obtain the access token and then to use that token and obtain the required record.

The first task is to install the axios plugin, for this within your Cypress test framework run the command npm install axios 

As we can see below, the axios npm plugin allows us to make GET/POST calls as required. Below example shows the use of the POST method. As shown below we pass the parameters of method,url and the required parameters to access the endpoint. We then use the .then to invoke the cypress promise and obtain the required access token. Once the access token is obtained we can use the axios again within the .then method to call the required API endpoint.

axios({
        method: 'post',
        url: 'https://localhost/auth/create/',
        data: {
            email: '<<user name>>',
            password: '<<password>>'
        },
        headers: {
        'Content-Type': 'application/json'
        },
      }).then(function (result) {
accessToken=result.data.access
axios({
        method: 'post',
        url: 'https://localhost/api/<<endpoint>>',
        data: {
            "period":{
               "from":"2020-10-10",
               "to":"2022-10-20"
            },
            "invoice_date":"2022-11-02",
            "notes":"test",
            "product":"abcd1234-1234-12345-abcdefg-123456"
         },
        headers: {
        'Content-Type': 'application/json',
        'Authorization': "Bearer " + accessToken
        }
     
once we have invoked the API call to obtain the required parameter we can then pass the required parameter to our cypress test as shown below

menuObject.getSearchField(result.data.invoice_number)

Comments