Cypress api分页查找对象



如何通过API分页来查找对象?例如:我有一个API "http://localhost:3000/users"返回:

{
"meta": {
"pagination": {
"total": 1645,
"pages": 83,
"page": 1,
"limit": 2
}
},
"data": [
{
"id": 1643,
"name": "m k",
"email": "mk@gmail.com",
"gender": "male",
"status": "inactive"
},
{
"id": 1643,
"name": "m k",
"email": "mk@gmail.com",
"gender": "male",
"status": "inactive"
}
]
}

我必须找到一个特定的用户。我如何在所有页面中执行请求以保证用户不存在?

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);
});
});

要重复多达10页,请将请求包装在调用自身的函数中,直到找到

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 })
})

你可能需要修改这个,这取决于在所有页面都被读取并且用户没有被找到后发生的情况

假设有5个用户页面,如果https://jsonplaceholder.typicode.com/users?page=6返回

  • status !== 200
  • 反应。
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 })
})

对于这些边缘条件将返回false,最终测试将在第10页失败。

最新更新