Cypress无法获取API响应数据,如何验证id与prevTrId?
解决Cypress中API响应断言'id'和'prevTrId'的问题
看你遇到的问题啦,你直接断言response.body有'id'属性肯定会报错,因为这个id根本不在根对象里。咱们先拆解下你的API响应结构:
{"result":{"code":200,"status":"OK"},"securities":[{"id":"3133H","sec":"USIG//FFCB","xcc":0,"liq":"9","dr":"-434.114562","dur":"5.411709","obs":[{"d":1549918953000,"bps":"0.001751","m":231,"prevTrId":"2019021AM_530","apc":{"tt":"-0.000328","tc":"0.001751","tta":"-0.033","tca":"0.175892"}}]}]}
错误原因
你当前代码里的断言expect(response.body).to.have.property('id', '3133H')是直接在根对象(也就是包含result和securities的对象)里找id,但实际上:
id位于response.body.securities数组的第一个元素中prevTrId又嵌套得更深,在response.body.securities[0].obs数组的第一个元素中
另外你提到cy.log只打印出{result: {code: 200, status: OK}, securities: [Object{7}]},这是因为Cypress默认不会展开嵌套对象,你可以用JSON.stringify来打印完整的响应内容,方便调试。
修正后的Cypress代码
describe('API Testing with Cypress', () => { it('Validate the header and nested properties', () => { cy.request('http://pTe-GPbt-ws.ga.data.com:9082/v1/testing/raw?dateFrom=01-01-2019&dateTo=07-17-2019&reqId=xxxxxx-secIds=3133EJ5H&tradeSizeFrom=10000&tradeSizeTo=5000&tradeSide=BUY&cepSide=BID&cepCompareToTrades=&cepCompareToQuotes') .then((response) => { // 打印完整响应内容,方便调试 cy.log(JSON.stringify(response.body, null, 2)); // 获取securities数组的第一个元素 const firstSecurity = response.body.securities[0]; // 断言id expect(firstSecurity).to.have.property('id', '3133H'); // 获取obs数组的第一个元素,断言prevTrId const firstObservation = firstSecurity.obs[0]; expect(firstObservation).to.have.property('prevTrId', '2019021AM_530'); }); }); })
额外提示
如果你的securities数组可能有多个元素,或者需要遍历验证,可以用Cypress的.each()方法来循环处理数组里的每一项;如果不确定数组是否为空,也可以先加一个断言确保securities数组长度大于0,避免出现索引越界的问题。
内容的提问来源于stack exchange,提问作者Smrutiranjana Ray
相关产品推荐
相关产品推荐

