我正在尝试验证如下所示的json:
{
"errors": false,
}
在邮递员上使用此
:var Ajv = require('ajv'),
ajv = new Ajv({logger: console, coerceTypes: false}),
schema = {
"errors": {
"type": "number"
}
};
pm.test('Schema is valid', function() {
var error = pm.response.json()['errors'];
console.log("this is error: " +error);
pm.expect(ajv.validate(schema, {errors: error})).to.be.true;
});
pm.test('Schema is valid different way', function() {
var error = pm.response.json()['errors'];
console.log("this is error: " +error);
var validate = ajv.compile(schema);
pm.expect(validate(pm.response.json())).to.be.true;
});
,但是它总是通过,即使我的错误对象是boolean
而不是number
。我在做什么错了?
注意:日志看起来像这样
this is error: false
答案 0 :(得分:1)
您可以使用Postman中的avj检查json模式,如下所示:
var Ajv = require('ajv'),
ajv = new Ajv({logger: console}),
schema = {
"properties": {
"errors": {
"type": "boolean"
}
}
};
pm.test('Schema is valid', function() {
var error = pm.response.json()['errors'];
pm.expect(ajv.validate(schema, {errors: error})).to.be.true;
});
数据:
{
"errors": false
}
结果:通过
数据:
{
"errors": true
}
结果:通过
数据:
{
"errors": 123
}
结果:失败
另一种方式
pm.test('Schema is valid', function() {
pm.expect(typeof(pm.response.json().errors) === "boolean").to.be.true;
});