我在 API 调用中请求了一个 POST 方法来进行登录测试,并收到了主体中包含许多对象的数组。我想使用 its 方法访问特定的客户端 token ,但它位于数组内部,我无法完全弄清楚如何访问,因为该数组没有“名称”。
cypress 中的请求:
it('Logar em um cliente com um usuário', function () {
cy.request({
method: 'POST',
url: 'https://localhost:44332/api/Users/LoginDefault',
body: {
"username": "user",
"password": "password"
}
}).its('body.token').then(res => console.log(res))
body react (恢复):
[
{
"user": "user1",
"token": "token1"
},
{
"user": "user2",
"token": "token2"
},
{
"user": "user3",
"token": "token3"
}
]
解决方案 它的工作原理如下:
it('Logar em um cliente com um usuário', function () {
cy.request({
method: 'POST',
url: 'https://localhost:44332/api/Users/LoginDefault',
body: {
"username": "user",
"password": "password"
}
}).its('body').then((res) => {
const dadoToken = res[1].token
expect(dadoToken).not.to.be.empty
})
})
最佳答案
在这种情况下,主体响应是一个数组,因此您需要做的就是导航该数组。
返回值是 res
,因此在这种情况下,它将是 res[i].token
,其中 i
是您需要的数组。
例如,res[2].token
将为“token3”。
关于arrays - Cypress:在 API 请求中访问数组内的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68457451/