邮递员始终对使用tv4的架构的响应始终有效

时间:2018-09-21 22:44:12

标签: javascript json rest postman tv4

我做了很多测试,但是我找不到解决的方法。简而言之,我有这个Postman测试脚本来验证JSON响应是否符合为此API定义的JSON模式:

const stockQuotesSchema = JSON.parse(pm.environment.get("schema"));

pm.test("Stock quote returns 200 OK", function () {
    pm.response.to.have.status(200);
})

pm.test("Stock quote is JSON", function () {
    pm.response.to.be.json;
})

pm.test("Stock quote response matches schema", function () {
    const validationResult = tv4.validateResult(pm.response.json(), stockQuotesSchema);
    pm.expect(validationResult.valid).to.be.true;
})

这是定义(简化)的API模式:

{
    "codexxx": "UNAUTHENTICATED",
    "messagexxx": "token expired"
}

这是我在运行请求后得到的响应:

{
    "code": "UNAUTHENTICATED",
    "message": "token expired"
}

由于架构中不存在“ code”字段和“ message”字段,因此我希望获得FAIL,但我始终会获取True。

This is the Postman result image

我需要使用长JSON模式验证每个响应(我的意思是比上面的示例更大的模式)。任何想法?谢谢。

1 个答案:

答案 0 :(得分:1)

您可以按照banUnknownProperties mode所述,通过附加的validateResult参数来强制实施(然后删除)here。例如:

const tv4 = require('tv4');

const schema = {
    properties: {
        codexxx: {
          type: 'string'
        },
        messagexxx: {
          type: 'string'
        }
    }
};

const invalidResponse = {
    code: 'UNAUTHENTICATED',
    message: 'token expired'
};

const validResponse = {
    codexxx: 'UNAUTHENTICATED',
    messagexxx: 'token expired'
};

const invalidRelaxedResult = tv4.validateResult(invalidResponse, schema);
const validRelaxedResult = tv4.validateResult(validResponse, schema);
const invalidStrictResult = tv4.validateResult(invalidResponse, schema, false, true);
const validStrictResult = tv4.validateResult(validResponse, schema, false, true);

console.log('Relaxed (invalid):', invalidRelaxedResult.valid);
console.log('Relaxed (valid):', validRelaxedResult.valid);
console.log('Strict (invalid):', invalidStrictResult.valid,
            invalidStrictResult.error.message, invalidStrictResult.error.dataPath);
console.log('Strict (valid):', validStrictResult.valid);

输出:

Relaxed (invalid): true
Relaxed (valid): true
Strict (invalid): false Unknown property (not in schema) /code
Strict (valid): true

validateResult的第三个参数指定是否进行递归检查。目前尚不清楚,但我相信默认值为false(如上例所示)。