I have been looking at many stack overflow solutions but none seem to fix my issue. I wrote code in my commands.js so I could use the json values I am trying to extract throughout my test suite. Here is the code I am using to do so:
Cypress.Commands.add('setAuthToken', () => {
cy.request('/this/is/my/jsonToken').then((res) => {
cy.wrap(res.body.token).as('token')
cy.get('@token').then((token) => {
cy.log(token)
})
})
})
Keeps saying the value is undefined. When I console log or cy log just the "res.body" it logs the correct json body object but as soon as I try to grab a property it becomes "undefined". Any suggestions or help welcomed.
There may be other factors at play, but I believe the core issue to be that the res.body is returned as a string, and not a JSON object. You can simply parse the object, and then you should be able to see the value.
Cypress.Commands.add('setAuthToken', () => {
cy.request('/this/is/my/jsonToken').then((res) => {
cy.wrap(JSON.parse(res.body).token).as('token')
cy.get('@token').then((token) => {
cy.log(token)
})
})
})
Note: this implementation only solves your main issue of having the res.body.token as undefined. It may not solve any issues on storing and referencing the value later. Without more information in the quest, I can't adequately provide a suggestion for that.