Reputation: 655
How can I paginate through an API to find an object? E.g: I have an API "http://localhost:3000/users" that return:
{
"meta": {
"pagination": {
"total": 1645,
"pages": 83,
"page": 1,
"limit": 2
}
},
"data": [
{
"id": 1643,
"name": "m k",
"email": "[email protected]",
"gender": "male",
"status": "inactive"
},
{
"id": 1643,
"name": "m k",
"email": "[email protected]",
"gender": "male",
"status": "inactive"
}
]
}
I have to find an specific user. How can I do the request in all pages to guarantee that the user don't exists?
it('Find the new user', () => {
cy.request({
method: "GET",
url: `https://localhost:3000/users?page=${pages}`
})
.then((response) => {
expect(response.body.code).to.equal(200);
expect(response.body.data.some(user => { return user.email === userToAdd.email })).to.eq(true);
});
});
Upvotes: 1
Views: 1001
Reputation:
To repeat up to, say 10 pages, wrap the request in function that calls itself until found
function getAllUsers(onResponse, page = 0) {
if (page === 10) throw 'User not found'
cy.request(`https://jsonplaceholder.typicode.com/users?page=${page}`)
.then(response => {
const found = onResponse(response)
if (found) return
getAllUsers(onResponse, ++page) // repeat for next page
})
}
getAllUsers(response => {
expect(response.status).to.eq(200);
const users = response.body.data;
return users.some(user => { return user.email === userToAdd.email })
})
You may have to modify this depending on what happens after all pages have been read and the user has not been found
Say there are 5 pages of users, if https://jsonplaceholder.typicode.com/users?page=6
returns
getAllUsers(response => {
const statusOk = response.status === 200;
const users = response?.body?.data; // optional chaining
return statusOk && users &&
users.some(user => { return user.email === userToAdd.email })
})
This will return false for those edge condition, and eventually the test will fail at page 10.
Upvotes: 2