繁体   English   中英

“邮递员-如何同时检查任何键的类型是'string'还是'null'”

[英]“Postman -How to check the typeof any key is 'string' or 'null' at same time”

在给定的响应片段中,“parentName”类型有时是null或有时是string 如何检查/编写测试用例以一次检查 typeof string以及null

tests["Verify parentName is string"] = typeof(jsonData.parentName) === "string" || null;

tests["Verify parentName is string"] = typeof(jsonData.parentName) === "string" || "null";
"demo": [
            {
                "id": 68214,
                "specializationId": 286,
                "name": "Radiology",
                "parentName": null,
                "primary": true
            }
        ],

如何在 postman (null & string) 中处理这种情况。

您需要检查 typeof jsonData.parentName是否为字符串或 (||) jsonData.parentName为 null

 tests = {}; jsonData = {parentName: null}; tests["Verify parentName is string"] = (typeof (jsonData.parentName) === "string" || jsonData.parentName === null) console.log(tests["Verify parentName is string"]); jsonData = {parentName: "test string"}; tests["Verify parentName is string"] = (typeof (jsonData.parentName) === "string" || jsonData.parentName === null) console.log(tests["Verify parentName is string"]);

我不推荐if elseif在 Postman 测试用例中。 Postman 具有用于模式检查的内置功能,您可以使用它并且可以在没有 if else 的情况下获得相同的结果。

首先,我正在考虑以下作为回应:

{
    "demo": [{
        "id": 68214,
        "specializationId": 286,
        "name": "Radiology",
        "parentName": null,
        "primary": true
    }]
}

Postman 测试应该是:

var Ajv = require('ajv'),
ajv = new Ajv({logger: console}),
schema = {
    "properties": {
        "parentName": {
            "type":["string", "null"]
        }
    }
};

pm.test('Verify parentName is string', function() {    
    var resParentName =  pm.response.json().demo[0].parentName;
    pm.expect(ajv.validate(schema, {parentName: resParentName})).to.be.true;
});

编辑:验证完整响应,而不仅仅是第一项。 还要检查响应中是否存在parentName

var Ajv = require('ajv'),
ajv = new Ajv({logger: console}),
schema = {
    "properties": {
        "demo":{
            "type": "array",
            "items": {
                 "properties": {
                     "id":{ "type": "integer" },
                     "specializationId":{ "type": "integer" },
                     "name":{"type": "string"},
                     "parentName":{
                         "type":["string", "null"]
                     },
                     "primary":{"type": "boolean"}
                 },
                 "required": [ "parentName"]
            }
        }
    }
};

pm.test('Validate response', function() {
    pm.expect(ajv.validate(schema, pm.response.json())).to.be.true;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM