I have to find a id from an array of objects with id, emails, birthday, etc
but i end up getting in the way
I thought of getting the index returned from the array, that has the right email/user (i.g: [email protected]), and then accessing and returning the id, or something like that
How can i do it properly?
Cypress.Commands.add('getId', (user, passwd) => {
// user = [email protected]
let arr = []
cy.getToken(user, passwd).then(token => {
cy.request({
method: 'GET',
url:'/users',
headers:{ Authorization: `Bearer ${token}` }
}).its('body.data.data').then((list) => Cypress._.map(list, 'email')).should('contain', '[email protected]')
.then(res => arr.push(res))
}).then(() => {
index = cy.log(arr.indexOf("[email protected]"))
return index
})//.its('body.id').then(id => {
//return id
//})
})
but this index return -1, and if i do cy.log(arr)
returns the proper array, so i can't test if i can access the body.id by it
My getToken code:
Cypress.Commands.add('getToken', (user, passwd) => {
cy.request({
method: 'POST',
url: '/auth/login',
body: {
email: user,
password: passwd
}
}).its('body.data.token').should('not.be.empty')
.then(token => {
return token
})
} )
CodePudding user response:
cy.log()
yields null. Try just returning the value instead of the one assigned.
.then(() => {
return arr.indexOf("[email protected]")
});
...
CodePudding user response:
You have your results array nested within another array.
See screen grab shows [Array(8)]
and item 0 is ['Leon', ...
So either:
Cypress.Commands.add("getId", (user, passwd) => {
let arr = []
cy.getToken(user, passwd)
.then((token) => {
cy.request({
method: "GET",
url: "/users",
headers: { Authorization: `Bearer ${token}` },
})
.its("body.data.data")
.then((list) => Cypress._.map(list, "email"))
.should("contain", "[email protected]")
.then((res) => arr.push(res));
})
.then(() => {
index = arr[0].indexOf("[email protected]")
cy.log(index)
return index;
});
})
or:
Cypress.Commands.add("getId", (user, passwd) => {
cy.getToken(user, passwd)
.then((token) => {
cy.request({
method: "GET",
url: "/users",
headers: { Authorization: `Bearer ${token}` },
})
.its("body.data.data")
.then((list) => Cypress._.map(list, "email"))
.should("contain", "[email protected]")
})
.then(arr => {
index = arr.indexOf("[email protected]")
cy.log(index)
return index;
});
})
Also .then((list) => Cypress._.map(list, "email"))
is dubious, the "email" is supposed to be a function.