javascript - 如何阻止在 Postman 上发送 undefined variable ?

标签 javascript json postman

我正在使用 Postman 使用 CSV 文件作为外部文件数据在 API 上运行测试。在CSV文件中,存在多个数据量不同的数据集,有的有数据,有的没有数据。当我运行集合运行程序并运行第一个数据集时,它失败,因为存在尚 undefined variable 并且 API 引发数据错误。

在 CSV 中

  1. 数据集 1

    • 订单, 客户编号, 条形码 1, 数量 1, 单价1
  2. 数据集2

    • 订单, 客户编号, 条形码 1, 数量 1, 单价 1, 条形码2, 数量 2, 单价2
  3. 数据集3

    • 订单, 客户编号, 条形码 1, 数量 1, 单价 1, 条形码2, 数量 2, 单价 2, 条形码 3, 数量 3, 单价3
In the body I've added that extra variables in case it is available in a data set.

{
  "order"  :  "{{orderId}}",
  "clientId" : "{{clientId}}",
  "skus"  :  [
        {
            "barcode": {{barcode1}},
            "quantity": {{quantity1}},
            "unitPrice": {{price1}}
        },
         {
            "barcode": {{barcode2}},
            "quantity": {{quantity2}},
            "unitPrice": {{price2}}
        },
         {
            "barcode": {{barcode3}},
            "quantity": {{quantity3}},
            "unitPrice": {{price3}}
        }
    ]

}

这是回复:

{
 "order" : "1000305408",
 "clientId" : "30",
 "skus" : [
 {
 "barcode": 123123123,
 "quantity": 1,
 "unitPrice": 100
 },
 {
 "barcode": {{barcode2}},
 "quantity": {{quantity2}},
 "unitPrice": {{price2}}
 }
 ]
} 

有没有办法阻止那些 undefined variable 键和数据,同时仍然将其保留在正文中,以防万一新数据集具有变量?

最佳答案

我们可以使用上传的 CSV 文件动态找出当前的集合数量。

我只是检查有多少个条形码集,并使用它来准备一个 setCount ,它将用于循环数据并创建 skus 项目。

预请求脚本:

_ = require('lodash');

// Here we'll know how many unit counts we have, I am checking barcode only.
let setCount = _.chain(data) // data is the actual iteration data from the csv file, don't worry just run the script.
    .keys()
    .countBy((item) => item.includes('barcode'))
    .value()
    .true,

    skus = [];


for(var i = 1; i <= setCount; i++) {
    skus.push({
        barcode: data[`barcode${i}`],
        quantity: data[`quantity${i}`],
        unitPrice: data[`unitprice${i}`]
    });
}

let requestBody = {
    order: data["orderId"],
    clientId: data["clientId"],
    skus: skus
};

pm.variables.set('requestBody', JSON.stringify(requestBody));

在您的请求正文选项卡中执行以下操作:

使用 JSON 将正文设置为原始,并添加 {{requestBody}} 作为正文中的变量。

如果有任何困惑,您可以引用屏幕截图。 raw json body

关于javascript - 如何阻止在 Postman 上发送 undefined variable ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55649051/

相关文章:

java - 如何从 JPBC 库中的 String 实例化 Element?

php - 如何限制 JSON 访问?

javascript - 找出测试失败的原因

api - Viber REST API,如何找到唯一的 Viber 用户 ID?

javascript - Angular.js。如何计算满足自定义过滤器的 ng-repeat 迭代次数

javascript - 从多个html select元素获取数据

javascript - Selenium Webdriver JavaScript : Promise seems to not be resolved

javascript - 简单的第一个 child js?

javascript - JSON 字符串中出现意外的空键值

c# - 如何使用 Postman 在 Web API 中调用函数?