Create test response from json OR directly access jsonSchema()

Good morning. I am trying to test my tests in postman, by testing an example subset of my data. Let’s assume that a normal response body is in the form of:

{
  categories: {[
      id: int,
      products: [int]
  ]}
} 

Without getting too bogged down in the specifics of that schema, I would like to write a test that works on a sample category, something like:

let sample_category = {id: 1, products: [1,2,3,4]};

Let’s also assume that I have defined the schema definition in a variable named schema_definition.

All the examples I’ve found test using a call to pm.response.to.have.jsonSchema(schema_definition). I would like to test directly against the variable sample_category, instead of pm.response. How can I either inject that sample response body into pm.response, or event better, simply test that sample_response is valid against schema_definition?

Thanks.

Hello @jdeasonphilz, Welcome to the Community :wave:

Yes you can do that using ajv. Please check here for more details.

You can save your sample response and the sample schema as two different variables, and can validate them.

var resp = pm.response.json();

var samplesubsetschema = 
{
..//define your schema
}

var sampleresp = //save the subset response against this;

pm.test('Schema validation using Ajv', function(){
    var Ajv = require('ajv');
    ajv = new Ajv({logger: console});
     pm.expect(ajv.validate(samplesubsetschema,sampleresp));
});

I hope this helps, I have just provided the rough scripts. If you still have any issues, kindly share the response and detailed screenshots :slight_smile:

2 Likes

Thank you very much. That’s perfect!!!

1 Like