How to make api request inside of test

Inside of an api test, i would like to get data from another api to compare against. ex;

Send GET request to abc.com/user

  • In the test section -

jsonData = pm.response.json()
pm.globals.set(“user”, jsonData.user)

pm.test(“User data is valid”, function () {

const getData ={
url: www.123.com/user,
method: ‘GET’,
header: {{ header}}

};

pm.sendRequest(getData);
jsonRes = pm.response.json()
pm.globals.set(“user2”, jsonRes.user)

pm.expect(user2).to.equal(user);

});

Even though i get a 200 on the call, the response, when logged, is not properly stored. Am i doing something wrong here?

What you’re doing wrong is that pm.sendRequest takes two parameters, the first is the request options and the second is the callback.

When you’re writing pm.response.json() it is referring the actual request that was being sent by postman, not the one that you explicitly defined in the test scripts.

What you need to do is this:

pm.sendRequest(getData, (err, response) => {
   let body = typeof response === 'string' ? JSON.parse(response) : response;
   pm.globals.set('user2', body.user);

  //and so on...
});