There is an API (referred to as getToken) that generates a token in its response body. This token is then called and stored in the header of another API (known as returnBody). It seems logical to utilize localStorage
for the getToken API since the token can be reused for multiple APIs. However, there are uncertainties about using localStorage
when it comes to returning or displaying the response body of subsequent APIs like returnBody. In the function/command of the API, the response body is logged. Yet, when invoked through the test file, it yields null.
Sample code provided below:
commands.js:
Cypress.Commands.add('getToken', () => { //API for token generation
cy.request({
method: 'POST',
url: 'https://someAPItoGenerateToken',
form: true, //set to application/x-www-form-urlencoded
body: {
grant_type: 'credentials',
scope: 'all-apis'
},
auth: {
username: Cypress.env('api_username'),
password: Cypress.env('api_password')
}
})
.its('body')
.then(bearerToken => {
cy.setLocalStorage('bearerToken', JSON.stringify(bearerToken))
cy.log('Token generated: ' + bearerToken.token)
}
)
})
Cypress.Commands.add('returnBody', (url, token) => { //API to retrieve certain values
return cy.request({
method: 'GET',
url: url,
auth: {
bearer: token
}
})
.then((response) => {
// Stringify the JSON body.
let body = JSON.stringify(response.body)
cy.log(body)
})
})
test file:
describe('Return value of 2nd API', ()=> {
before(() => {
cy.getToken() //Execute this once to generate token for the entire test suite
cy.saveLocalStorage()
})
beforeEach(() => {
cy.restoreLocalStorage()
})
it('Return value of 2nd API', () => {
cy.getLocalStorage('bearerToken').should('exist')
cy.getLocalStorage('bearerToken').then(bearerToken => {
const tokenJSON = JSON.parse(bearerToken)
const url = 'https://someAPItoReturnJSONbody'
cy.returnBody(url, tokenJSON.token).then((returned_value) => {
cy.log(returned_value)
})
})
})
})
The body returned by the returnBody command consists of the JSON response. Nonetheless, the returned_value from the test file shows null.