如何在Cypress中实现请求链?OpenWeather API响应验证失败
OpenWeather API测试匹配失败问题解决
我正尝试验证OpenWeather API的响应,测试步骤如下:
- 通过POST请求创建气象站
- 从步骤1的POST响应中获取外部ID
- 将该外部ID与GET请求的响应进行匹配,匹配成功则测试通过,未找到则测试失败
当前编写的Cypress测试代码如下,但匹配环节出现失败:
it.only('first POST and array iteration', () => { cy.request({ method: 'POST', url: 'https://api.openweathermap.org/data/3.0/stations?appid=7fe67bf08c80ded756e598d6f8fedaea', headers: { 'Accept': 'application/json' }, body: { "external_id": "testweatherapi12", "name": "weather_api12", "latitude": 35.55, "longitude": 89.45, "altitude": 56.4 } }).then((res) => { cy.log('response is ' + JSON.stringify(res)); let idIs = res.body.ID; cy.log('ID****** is ' + idIs); expect(res.status).to.eq(201) }).then((res) => { cy.request({ method: 'GET', url: 'https://api.openweathermap.org/data/3.0/stations?appid=7fe67bf08c80ded756e598d6f8fedaea', headers: { 'Accept': 'application/json' } }).then((res) => { for (var x = 0; x < res.body.length; x++) { expect(res.body[x].id).to.eq(res.body.ID); //This is failing } }) }) })
问题分析
- 变量作用域失效:第一个
.then()里定义的idIs,在后续.then()中无法访问,因为每个.then()的作用域相互独立。 - 匹配逻辑错误:循环中用
res.body[x].id和res.body.ID对比,但GET响应是数组,不存在ID属性,且这个res是GET请求的响应,根本不是POST返回的目标ID。另外需求是匹配external_id,但代码里误用了id/ID字段。 - 循环断言逻辑错误:循环逐个断言所有元素等于目标ID,只要有一个不匹配就失败,不符合“存在匹配即通过”的测试要求。
修正后的代码
it.only('first POST and array iteration', () => { cy.request({ method: 'POST', url: 'https://api.openweathermap.org/data/3.0/stations?appid=7fe67bf08c80ded756e598d6f8fedaea', headers: { 'Accept': 'application/json' }, body: { "external_id": "testweatherapi12", "name": "weather_api12", "latitude": 35.55, "longitude": 89.45, "altitude": 56.4 } }).then((postRes) => { cy.log('POST响应: ' + JSON.stringify(postRes)); expect(postRes.status).to.eq(201); // 若需求是匹配external_id,替换为postRes.body.external_id const targetId = postRes.body.ID; cy.log('创建的气象站ID: ' + targetId); return cy.request({ method: 'GET', url: 'https://api.openweathermap.org/data/3.0/stations?appid=7fe67bf08c80ded756e598d6f8fedaea', headers: { 'Accept': 'application/json' } }).then((getRes) => { // 检查数组中是否存在匹配的ID const isMatch = getRes.body.some(station => station.id === targetId); // 匹配external_id的话改为:station.external_id === postRes.body.external_id expect(isMatch).to.be.true; }); }); });
修正说明
- 变量传递优化:在POST响应的
.then()中直接发起GET请求,通过return传递上下文,确保能访问POST返回的目标ID。 - 匹配逻辑修正:用数组
some()方法检查存在性,只要有一个元素匹配就返回true,符合测试通过条件。 - 字段对应修正:POST响应的ID是
ID(大写),GET响应每个元素的ID是id(小写),确保字段名对应正确;若需求是匹配external_id,直接替换字段名即可。 - 避免无效断言:去掉循环逐个断言的逻辑,改用存在性检查,更高效且符合测试需求。
内容的提问来源于stack exchange,提问作者nikhil udgirkar
相关产品推荐
相关产品推荐

