【发布时间】:2021-05-02 21:15:45
【问题描述】:
我的 Web 应用程序发送 API POST 请求以创建应用程序并返回 JSON 响应。我想从该响应中访问一个特定的 JSON 对象。 我的 JSON 是这样开始的
[
{
"status_code": 201,
"body": {
"created": "2021-01-28T00:00:00Z",
"modified": "2021-01-28T00:00:00Z",
"id": "a2d86d17-9b3c-4c4d-ac49-5b9d8f6d6f8f",
"applicant": {
"id": "07f1e1d3-0521-401b-813e-3f777f2673c6",
"status": "Pending",
"first_name": "",
"last_name": "",
"URL": "some onboarding url"
我想在 JSON 响应中获取该 URL,稍后在我的 cypress 自动化脚本中访问它。 请注意,JSON 响应以方括号而不是花括号开头,这意味着,我假设整个响应是一个对象?
我的柏树脚本是这样的
cy.contains('button', 'CONTINUE').click()
cy.EmailGen('candidate').then(email => {
cy.get('#emails\\[0\\]').type(`${email}`)
cy.wrap(email).as('candidateEmail')
})
//writing intercept here, before the Send application button, which triggers the POST req.
cy.intercept('/hr/v1/applications/invite').as('getURL')
cy.get('button').contains('SEND APPLICATION').click({ force: true })
//waiting on the alias of intercept and using interception to print objects from response
cy.wait('@getURL').then((interception)=> {
cy.log(interception.response.body.applicant.URL)
})
cy.Logout()
脚本执行没有错误。只是在 cy.log 语句中没有记录任何内容。下面是画面。
cy.intercept('/hr/v1/applications/invite',(req) => {
req.reply((res=> {
expect(res.status_code).to.equal('201')
expect(res.body.applicant.status).to.equal('Pending')
}))
})
在这种情况下,我在请求和响应中嵌入了一个断言错误,以及我无法理解的其他一些内容。 完整的错误是这样的...... "预期以下错误源自您的测试代码,而不是赛普拉斯。\n\n > 传递给 req.reply() 的响应回调在拦截响应时引发错误:\n\n预期未定义等于 '201'\n \nRoute: {\n "matchUrlAgainstPath": true,\n "url": "/hr/v1/applications/invite"\n}\n\n拦截的请求:{} 拦截的响应:{} 当赛普拉斯检测到源自未捕获的错误时从您的测试代码中,它会自动使当前测试失败。包含 window.zE 不是函数"
读起来有点奇怪..
我的应用程序有时会抛出此异常,我已使用以下代码进行了处理。
cy.on('uncaught:exception', (err, runnable) => {
expect(err.message).to.include('window.zE is not a function')
done()
return false
})
我真的希望我已经解释了这里的一切。请帮助一个菜鸟。 问候
【问题讨论】:
-
这意味着,整个响应是一个对象 - 不,它是一个对象数组。从
cy.log(interception.response)开始,然后从那里处理数据(可能console.log(interception.response)更好)。 -
谢谢理查德!根据您的建议,最初我只尝试过(interception.response)...检查了控制台中的输出...了解了它的外观...并修改了json遍历...interception.response.body [0 ].body.applicant.URL
标签: json exception response cypress intercept