[英]“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.