jsonpostmanweb-api-testing

Comparing entire response body in Postman, while it has JSON DataSchema


I'm quite new to Postman, and trying to create Automation Script to create an object that contains JSON Schema. But I'm getting an error which I'm not sure how to bypass.

Can you please help?

Here is my expected response script:

    pm.test("Body is correct", function () {
    pm.response.to.have.body("{\"Id\":"+typeId+",\"NamespaceId\":"+namespaceId+",\"Name\":\"Auto Test\",\"DataSchema\":\"\{\n    \"firstName\": {\n           \"type\": \"string\",\n           \"description\": \"The person\u0027s first name.\"\n    \}\n}\",\"Code\":\"AUTOTYPE\"}");
});

Here is the actual response (Body):

    {
    "Id": 1059,
    "NamespaceId": 1089,
    "Name": "Auto Test",
    "DataSchema": "{\r\n  \"firstName\": {\r\n    \"type\": \"string\",\r\n    \"description\": \"The person's first name.\"\r\n  }\r\n}",
    "Code": "AUTOTYPE"
}

Here is an error I'm getting:

Body is correct | AssertionError: expected response body to equal '{"Id":1059,"NamespaceId":1089,"Name":"Auto Test","DataSchema":"{\n "firstName": {\n "type": "string",\n "description": "The person\'s first name."\n }\n}","Code":"AUTOTYPE"}' but got '{"Id":1059,"NamespaceId":1089,"Name":"Auto Test","DataSchema":"{\\r\\n \\"firstName\\": {\\r\\n \\"type\\": \\"string\\",\\r\\n \\"description\\": \\"The person\\u0027s first name.\\"\\r\\n }\\r\\n}","Code":"AUTOTYPE"}'

Here is the actual part of create script:

    {  "NamespaceId": 1089,
  "Name": "Auto Test",
  "Code": "AUTOTYPE",
  "DataSchema": {
    "firstName": {
           "type": "string",
           "description": "The person's first name."
    }
}
 }

Thanks in advance.

P.S. I tried to put more \ but then Postman would complain.


Solution

  • I think the problem is that you specify that you expect a string as a body, but than compare it to a JSON object. The way you've set it up now, the test is very brittle, more so than it needs to be IMHO.

    A little more coding will give you a solution that is way more stable (e.g. doesn't depend on whitespace formatting, which is irrelevant to JSON):

    pm.test("Body is correct", function () {
        const jsonData = pm.response.json();
        pm.expect(jsonData.Id)
            .to.be.a('number', 'Id should be a number')
            .that.is.equal(typeId, 'Id should equal typeId');
        pm.expect(jsonData.NamespaceId)
            .to.be.a('number', 'NamespaceId should be a number')
            .that.is.eql(namespaceId);
        pm.expect(jsonData.Name).to.equal("Auto Test");  
    
        // is this really what you want, i.e. should this be a string?
        pm.expect(jsonData.DataSchema).to.be.a('string'); 
        const dataSchema = JSON.parse(jsonData.DataSchema);
        pm.expect(dataSchema.firstName.type).to.equal("string");
        // ... etc    
    });