Postman测试/api/v1/shopping-cart接口时出现断言错误与类型错误求助
Postman测试/api/v1/shopping-cart接口时出现断言错误与类型错误求助
各位大佬好!我在用Postman测试/api/v1/shopping-cart接口的时候碰到了两个棘手的问题,折腾半天没理清原因,来请大家帮忙分析下:
错误详情
首先接口返回了500状态码,直接触发了断言失败,同时还伴随一个类型错误,具体提示如下:
Response code 200 or 201 | AssertionError: expected 500 to be one of [ 200, 201 ]
Checking product availability and quantity validity | TypeError: Cannot read properties of undefined (reading 'hasOwnProperty')
接口返回的500错误完整响应:
{ "timestamp": "2025-03-29T01:59:18.976+00:00", "status": 500, "error": "Internal Server Error", "path": "/api/v1/shopping-cart" }
Pre-request 前置脚本
我在请求前做了测试数据的准备工作,脚本代码如下:
const main = async () => { const api = new API(pm); const rnd = new RandomUtils(); try { pm.collectionVariables.set("userName", rnd.getWord(10)); product1 = rnd.getProductForWarehouse(); product2 = rnd.getProductForWarehouse(); await api.addProductToWarehouse(product1); await api.addProductToWarehouse(product2); productList = { [product1.productId]: Math.floor(Math.random() * 1000), // Случайное число до 1000 [product2.productId]: Math.floor(Math.random() * 1000) // Случайное число до 1000 }; pm.collectionVariables.set("productList", productList); // Сохраняем productList, если нужно } catch (err) { console.error("Ошибка при подготовке тестовых данных.", err); } pm.request.body.update({ mode: 'raw', raw: JSON.stringify(productList), options: { raw: { language: 'json' } } }); }; const interval = setInterval(() => {}, 1000); setTimeout(async () => { try { await main(); } catch (e) { console.error(e); } finally { clearInterval(interval); } }, 100 );
Post-response 后置断言脚本
请求完成后的校验脚本是这样写的:
pm.test("Код ответа 200 или 201", function () { pm.expect(pm.response.code).to.be.oneOf([200, 201]); }); const productList = pm.collectionVariables.get("productList"); const products = pm.response.json().products; pm.test("Проверка наличия продуктов и валидности количества", function () { let allKeysPresent = true; let valuesValid = true; for (key in productList) { if (!products.hasOwnProperty(key)) { allKeysPresent = false; break; } if (products[key] < productList[key]) { valuesValid = false; } } pm.expect(allKeysPresent).to.be.true; pm.expect(valuesValid).to.be.true; });
现在我有两个核心疑问:
- 接口为什么会返回500内部错误?会不会是前置脚本里的测试数据准备环节出了问题?
- 那个类型错误是不是因为接口返回500后,响应体里根本没有
products字段导致的?有没有办法优化断言逻辑,先判断响应状态码正常后再做结构校验?
麻烦各位帮忙看看,谢谢啦!
备注:内容来源于stack exchange,提问作者dddsssvvv
相关产品推荐
相关产品推荐

