【问题标题】:Postman check for two decimal places for a number in a test邮递员在测试中检查数字的两位小数
【发布时间】:2021-04-08 14:29:17
【问题描述】:

我遇到的情况是我正在做一个基本测试,并且看起来 response.json() 正在截断尾随零。由于这是一个货币字段,我想验证响应是否发送了那些零。这是我的例子:

原始回复:

    .
    .
    "amount": 100.00,
    .
    .

运行转换后:

    const responseJson = pm.response.json();

这行写着:

    .
    .
    "amount":100,
    .
    .

我不再能够测试它最初是否有两位小数。

为了它的价值,我开始了转换为字符串的路径,但它在到达 pm.expect 语句时已经被截断,所以我无法对其进行正则表达式。

除了试图让 api 的发起者返回一个字符串而不是一个数字之外的任何解决方案(我不喜欢这样的原因有很多)。

【问题讨论】:

    标签: json numbers postman truncation


    【解决方案1】:

    经典的 JavaScript。试图强迫您为看似简单的事情制定个性化的解决方法:)

    编辑:假设您不需要担心舍入...

    var amount = pm.response.json().yourPathTo.amount.toFixed(2);
    
    console.log(amount); // "100.00"
    

    注意,由于 toFixed 函数的返回类型,对象类型是字符串。

    var response = {
        "product": "juice",
        "amount": 100.00,
        "stock?": true
    };
    
    console.log(typeof response.amount.toFixed(2), response.amount.toFixed(2)); // "string" "100.00"
    
    console.log(typeof parseInt(response.amount.toFixed(2)), response.amount.toFixed(2)); // "number" "100.00"
    
    console.log(typeof parseFloat(response.amount.toFixed(2)), response.amount.toFixed(2)); // "number" "100.00"
    

    在响应正文中以字符串形式返回金额可能是我(个人)会选择的路线。但是,我相信这就是您想要的。

    如果你需要考虑四舍五入,使用这个:

    function roundToTwo(num)
    {
        return +(Math.round(num + "e+2")  + "e-2");
    }
    

    感谢MarkG对此question的回复

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 2021-02-21
      • 2019-10-06
      • 2020-01-04
      • 2020-06-19
      • 2020-11-19
      • 2016-07-20
      • 2021-05-12
      • 2018-01-26
      相关资源
      最近更新 更多