Search code examples
jsongetbddpostman

accessing json in postman BDD syntax


I am trying to write tests (GET requests) in BDD syntax as in https://www.npmjs.com/package/postman-bdd

The json response can be as below which can be displayed in postman using console.log(response.body);

{
    "Id1": {
        "a": 84,
        "b": 74,
        "c": 7,
        "d": 3,
        "e": 91
    },
    "Id2": {
        "a": 25,
        "b": 51,
        "c": 93,
        "d": 97,
        "e": 1
    }
}

Pls let me know how can I access the value of keys like a,b,c for Id1 and Id2 in BDD syntax.

I tried console.log(response.body.Id1); and console.log(response.body.Id1.a) and both does not work.


Solution

  • You need to reference the postmanBDD module with an eval() statement, in your test. This needs to be saved as a postman global variable in order to work.

    eval(globals.postmanBDD)
    
    var jsonData = pm.response.json()
    
    describe('Get Ids', () => {
    
      it('should return the correct Id', () => {
        expect(jsonData.Id1.a).to.equal(84)
      })
    })
    

    This is a basic example of extracting data from JSON objects.

    As an alternative, you can now do the same thing in the latest Postman app without bringing in the external PostmanBDD module:

    pm.test('Get Id value', () => {
        var jsonData = pm.response.json()
        pm.expect(jsonData.Id1.a).to.equal(84)
    })
    

    This test code would do the same as the first solution.