You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Postman中使用Chai jsonSchema如何实现字段多类型校验?

基础多类型校验实现

JSON Schema 的 type 关键字支持传入数组,同时声明多个允许的匹配类型,你只需要修改 data 和 err 字段的类型配置即可,修改后的测试代码如下:

pm.test("Check response schema", () => {
    const schema = {
        "type": "object",
        "properties": {
            "success": { "type": "boolean" },
            "data": { "type": ["object", "null"] },
            "err": { "type": ["object", "null"] },
            "info": { "type": "string" }
        },
        "required": ["success", "data", "err", "info"]
    }
    pm.response.to.have.jsonSchema(schema)
})

以上方案可以满足允许多种类型的基础需求。

更贴合业务逻辑的优化方案

上述基础方案存在缺陷:没有结合success字段的业务含义做校验,会允许success=true但data=null、err=object这类不符合业务规则的异常响应通过校验。
你可以使用JSON Schema的if/then/else关键字实现分支校验,完全匹配业务逻辑,优化后的代码如下:

pm.test("Check response schema", () => {
    const schema = {
        "type": "object",
        "properties": {
            "success": { "type": "boolean" },
            "info": { "type": "string" }
        },
        "required": ["success", "data", "err", "info"],
        "if": {
            "properties": { "success": { "const": true } }
        },
        "then": {
            "properties": {
                "data": { "type": "object" },
                "err": { "type": "null" }
            }
        },
        "else": {
            "properties": {
                "err": { "type": "object" },
                "data": { "type": "null" }
            }
        }
    }
    pm.response.to.have.jsonSchema(schema)
})

该方案会严格校验业务逻辑一致性,相比基础方案校验严谨性更高。

内容的提问来源于stack exchange,提问作者Bamba675

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:09:03