如何使用POSTMAN测试对象的大小是否大于特定数字

时间:2017-11-20 06:13:29

标签: javascript postman

我正在尝试在POSTMAN中进行测试,其中大小必须大于0,但我无法正确进行测试。

我所做的是在尺寸小于0时使其失败。

邮递员是否有功能检查尺寸是否大于x数?

    pm.test("Step 7/ Getting the resources and availabilites list " , function(){

    pm.expect(pm.response.code).to.be.oneOf([200]);
    if(pm.response.code === 200){
        var jsonData = JSON.parse(responseBody);
        var sizeOK= 1;
        if(jsonData.resources.length>0){

        }else{
            //I will make the test fail if there is not data available on the response.
            pm.test("Response body is empty ", function () {
                pm.expect(pm.response.json().resources.length).to.equal(1);
            });

        }
        console.log(Boolean(jsonData.resources.length>1))
    }

});

3 个答案:

答案 0 :(得分:12)

pm.expect(pm.response.json().resources.length).to.be.above(0);

请参阅http://www.chaijs.com/api/bdd/

答案 1 :(得分:2)

Postman使用chai库的扩展实现。 你可以在这里查看源代码: https://github.com/postmanlabs/chai-postman

因此逻辑上,当您抛出错误并且测试捕获它时,测试才会失败。 它只是通过。 所以expect调用实际上会抛出一个错误,导致测试失败。 如果你只是返回任何东西或者什么都不返回,那么即使这样,测试也会通过。

考虑一个简单的try和catch块。 因此,要立即解决您的问题,您可能会抛出错误而您的测试将失败。

您可以像这样修改代码:

pm.test("Step 7/ Getting the resources and availabilites list " , function(){

    pm.expect(pm.response.code).to.be.oneOf([200]);
    if(pm.response.code === 200){
        var jsonData = JSON.parse(responseBody);
        var sizeOK= 1;
        if(jsonData.resources.length>0){

        } else {
            pm.test("Response body is empty ", function () {
               throw new Error("Empty response body"); // Will make the test fail.
            });

        }
        console.log(Boolean(jsonData.resources.length>1))
    }

});

另外,你可以另外使用简单的javascript来轻松测试长度/大小(仅举例):

pm.test("Step 7/ Getting the resources and availabilites list " , function(){

        pm.expect(pm.response.code).to.be.oneOf([200]);
        if(pm.response.code === 200){
            var jsonData = JSON.parse(responseBody);
            var sizeOK= 1;
            if(jsonData.resources.length>0){

            } else {
                pm.test("Response body is empty ", function () {
                   if(jsonData.length < 3) {
                      throw new Error("Expected length to be greater than 3");
                   }
                });

            }
            console.log(Boolean(jsonData.resources.length>1))
        }

    });

答案 2 :(得分:0)

虽然我不确定您需要的精确度,但您会在Postman中获得响应大小。它由Body Size和Headers size组成(只需指向应用程序中的Size&#39; s值)。在您的测试区域中,您可以恢复身体尺寸:

var size=0;
for (var count in responseBody) {
    if(responseBody.hasOwnProperty(count))
        size += 1;
}
console.log("BODY SIZE = " + size); // you'll see the correct value in the console for the body part

然后针对此值进行测试......