【问题标题】:"Postman -How to check the typeof any key is 'string' or 'null' at same time"“邮递员 - 如何同时检查任何键的类型是‘字符串’还是‘空’”
【发布时间】:2019-11-08 07:02:31
【问题描述】:

在给定的响应中,sn-p "parentName" 类型有时是 null 或有时是 string。如何检查/编写测试用例以一次检查 stringnull 的类型。

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
            }
        ],

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

【问题讨论】:

  • 您是否尝试在 javascript 中编写代码来识别类型?
  • 是的,我正在尝试用 js 编写代码
  • 所以你可以这样做 - jsonData.parentName === null || typeof jsonData.parentName === 'string'
  • @Kaushik 我试过这个,它对我有用。但后来我只是将类型从“字符串”更改为数字(仅用于测试目的)jsonData.parentName === null || typeof jsonData.parentName === 'number' 仍然显示通过的结果。它应该是正确的。
  • 你可以尝试使用if elsif and else block。

标签: javascript postman postman-testcase


【解决方案1】:

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

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

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

邮递员测试应该是:

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;
});

【讨论】:

  • 嘿需要小帮助我得到错误Error: Cannot find module 'ajv' 然后我尝试了npm install ajv 但仍然得到同样的错误。请告诉我该怎么做。
  • @Akshay77:你的 Postman 版本是什么。无需安装 npm 包
  • 那不是只检查第一个对象吗,如果还有更多呢?如果 parentName 从响应中删除,我相信它仍然会通过。
  • 感谢@DannyDainton ?? 指出我错过的边缘情况。答案更新!让我知道是否还有什么遗漏:)
猜你喜欢
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多