如何从Cypress拦截的响应体中获取动态嵌套ID值?
问题:从Cypress拦截的API响应深层对象中获取动态键名的ID
我尝试从Cypress拦截的API响应体的深层对象结构中获取一个ID值。该ID作为对象的键名存在,且会随登录账户不同而变化。我的Cypress代码如下:
cy.intercept('GET', 'https://api.staging.ethicalstg.com.au/organisations/*').as('search') cy.wait('@search').its('response.body') .then((body) => { cy.log(body.data.entities.users) })
日志返回的body.data.entities.users是一个以ID为键名的对象(而非数组),我曾尝试用cy.log(body.data.entities.users[0])获取ID,但返回空值,请问该如何获取这个ID?
解决方案
因为body.data.entities.users是对象类型,不是数组,所以不能用数组索引[0]访问。可以通过Object.keys()方法提取对象的所有键名(也就是你要的ID),具体代码如下:
cy.intercept('GET', 'https://api.staging.ethicalstg.com.au/organisations/*').as('search') cy.wait('@search').its('response.body') .then((body) => { // 获取users对象的所有键名(即ID),返回一个数组 const userIds = Object.keys(body.data.entities.users) // 如果只有一个用户ID,取数组第一个元素 if (userIds.length > 0) { const targetUserId = userIds[0] cy.log('获取到的用户ID:', targetUserId) // 若需要获取该ID对应的用户详情数据 const userDetail = body.data.entities.users[targetUserId] cy.log('用户详情:', userDetail) } })
补充说明
Object.keys(对象)会返回该对象所有可枚举键名组成的数组,刚好匹配你需要的动态ID场景- 如果接口返回的users对象可能包含多个ID,可以通过遍历
userIds数组来处理每个ID
内容的提问来源于stack exchange,提问作者Stephen Senjaya
相关产品推荐
相关产品推荐

