How to check if the response is received in a sort order

I have a Json response with employees information. I want to check if the response is sorted by firstname.
ex:
{
ā€œemployeesā€: [
{
ā€œfirstnameā€: ā€œScottā€,
ā€œlastnameā€: ā€œBartelsā€,
ā€œidā€: 12345
},
{
ā€œfirstnameā€: ā€œAaronā€,
ā€œlastnameā€: ā€œClareā€,
ā€œidā€: 77845
},
{
ā€œfirstnameā€: ā€œVictorā€,
ā€œlastnameā€: ā€œDraneā€,
ā€œidā€: 12775
}
]
}

@Aparna.AA You can make use of lodash which is built right into Postman.

You can put the following script in your Tests script tab:

var _ = require('lodash'),
   // Hardcoding response body for this example. Replace it with your original response body.
    responseBody = {
        "employees": [{
            "firstname": "Scott",
            "lastname": "Bartels",
            "id": 12345
        }, {
            "firstname": "Aaron",
            "lastname": "Clare",
            "id": 77845
        }, {
            "firstname": "Victor",
            "lastname": "Drane",
            "id": 12775
        }]
    };


pm.test('Employee names are in sorted order', () => {
   // Using the orderBy function from lodash 
   // Read docs: https://lodash.com/docs/4.17.10#orderBy
    var expectedSortedOrder = _.orderBy(responseBody.employees, ['firstname'],['asc']);

    pm.expect(responseBody.employees).to.eql(expectedSortedOrder);    
});

The above test will fail because obviously the hardcoded values are not sorted.
Once youā€™ll replace it with correct values, the test will pass.

5 Likes

Thanks @singhsivcan. This is very helpful.

How to traverse if there was no name to the object
ex:
[
{
ā€œlinksā€: [{
ā€œrelā€: ā€œeditā€,
ā€œhrefā€: ā€œxxxxx1ā€
}],
ā€œidā€: ā€œ9c94163d4ae2ā€,
ā€œfirstnameā€: ā€œNobleā€,
ā€œlastnameā€: ā€œBerlinā€
},
{
ā€œlinksā€: [{
ā€œrelā€: ā€œeditā€,
ā€œhrefā€: ā€œxxxxx2ā€
}],
ā€œidā€: ā€œ9c94163d4ae2ā€,
ā€œfirstnameā€: ā€œHumbleā€,
ā€œlastnameā€: ā€œBerlinā€
},
{
ā€œlinksā€: [{
ā€œrelā€: ā€œeditā€,
ā€œhrefā€: ā€œxxxxx3ā€
}],
ā€œidā€: ā€œ9c94163d4ae2ā€,
ā€œfirstnameā€: ā€œBumbleā€,
ā€œlastnameā€: ā€œBerlinā€
}
]

@Aparna.AA By ā€˜no nameā€™ to the object, do you mean the employees key is not there?
And the response that was returned is an array?

You can still do that over the response that was returned.
Updated the script for that:

var _ = require('lodash'),

    // Parse the array returned in the response body (It is probably a stringified response)
    responseArray = JSON.parse(responseBody);

pm.test('Employee names are in sorted order', () => {
    // Use the responseArray here
    var expectedSortedOrder = _.orderBy(responseArray, ['firstname'],['asc']);

    pm.expect(responseArray).to.eql(expectedSortedOrder);
});

Thank you Sivcan! :+1:

1 Like

@singhsivcan - I appreciate your above response. However, I just got a quick question. In order to verify if the sorting is in descending order then should we replace asc with desc? If not, then can you please let me know how to verify if itā€™s in descending order? Your prompt response will be highly appreciated. Thank you! :slight_smile:

Hi @yeaser.khan, yeah you guessed it right - just replace asc with desc.
Well, itā€™s a library called lodash that is built into postman and orderBy is a function that belongs to that library.
You can read the documentation here: https://lodash.com/docs/4.17.11#orderBy

1 Like

@singhsivcan - Thank you so much for your quick response.

Hi @singhsivcan,

Your answer helped me a lot, thanks. I have just a problem when setting orderBy for a text field that may contain non-Ascii character such as Ć©, ĆŖ Ć . It seems that lodash does not take into consideration the charset of the response.

Do you know of a way to work around that?

Thanks!

Hi @fulasNator, welcome to the community! :wave:

I guess you can try using deburr and then sort it out.
You can refer the lodash docs for using deburr, converting your strings and then work your way out for sorting.

Hi @singhsivcan,

thanks for you fast reply! It worked with .deburr. I used it in conjunction with the orderBy:

var testSortOrder = _.orderBy(peopleArray, (people) => {return _.deburr(people.Name)}, ['asc']);

Thank your very much!

1 Like

I get weird results. when i try to use the sort methods.

so i have a very simple response
[
{
ā€œcompanyIdā€: ā€œ123ā€,
ā€œeidā€: 29901199,
ā€œuserNameā€: ash,
ā€œemployeeIdā€: ā€œ10402ā€,
ā€œenabledā€: true,
ā€œlastNameā€: ā€œjillā€,
ā€œfirstNameā€: ā€œeffortā€,
ā€œsupervisorNameā€: null,
ā€œsupervisorIdā€: null,
ā€œcc1ā€: ā€œtestā€,
ā€œcc2ā€: ā€œtestā€,
ā€œemailAddressā€: ā€œeffort@gmail.comā€,
ā€œuserTypeā€: 1,
ā€œuserTypeDescriptionā€: ā€œRegularā€
},
same structure repeats.

my request url is v1/co/1/user?sort=userName:desc

and in my test tab for assertion i have


var _ = require(ā€˜lodashā€™),

  responseArray = JSON.parse(responseBody);

pm.test(ā€˜Employee names are in sorted orderā€™, () => {

var expectedSortedOrder = _.orderBy(responseArray, ['userName'],['desc']);

pm.expect(responseArray).to.eql(expectedSortedOrder);

});


no matter what i change the sort order from desc to asc on line (var expectedSortedOrder = _.orderBy(responseArray, [ā€˜userNameā€™],[ā€˜descā€™]);)) the test always passes.
occasionally I also get this error

Employee names are in sorted order | AssertionError: expected [ Array(25) ] to deeply equal [ Array(25) ]

what am I doing wrong.
Most importantly how do I test the sort is validated in response as indicated in the request url?.

same problem bro, no matter how i change the response name and sorting type, the result are always pass, for example:

pm.test(ā€œShowing Data from the Last Investorā€, function () {
var expectedSortedOrder = sortData.orderBy(responData.data, [ā€™ā€™],[ā€™ā€™]);
pm.expect(responData.data).to.eql(expectedSortedOrder);
});

The result will pass

When I have numbers I had used this code:
const jsonData = JSON.parse(responseBody);

pm.test(ā€œAscending sortā€, function () {
jsonData.sessions.reduce((prev,current) => {
pm.expect(prev.id).to.be.above(current.id);
console.log(prev.id, current.id)
return current;
});
});

Hi sivcan,

I tried to use lodash for my issue but it didnā€™t work.

I am working with an API and I want the response to be sorted by the views objects in numerical descending order.

I used this code as a pre-request script but it gives an error. Help, please?

var r = JSON.parse(responseBody)

var z = r.results.views.sort(function(x, y) {

return x - y;

});

console.log(r)

I need to check if the response received is in a sorted order of name property.

I used the below script and I am getting the error as ā€œAssertionError: expected undefined to deeply equal []ā€

var _ = require(ā€˜lodashā€™)
pm.test(ā€˜Names are in sorted orderā€™, () => {
var expectedSortedOrder = _.orderBy(responseBody.objects, [ā€˜nameā€™],[ā€˜ascā€™]);

pm.expect(responseBody.objects).to.eql(expectedSortedOrder);    

});

The response body is :

{
ā€œpageā€: 0,
ā€œpageSizeā€: 0,
ā€œtotalItemsā€: 68,
ā€œmaxPageSizeā€: 0,
ā€œobjectsā€: [
{
ā€œcomponentIdā€: 1150,
ā€œnameā€: ā€œABCDā€,
},
{
ā€œcomponentIdā€: 1200,
ā€œnameā€: ā€œEFGHā€
}
]
}

Anyone please help me to understand the issue.

@Akshatha_B_A Welcome to Community!! :bouquet:

Its because you are trying to access the response without parsing it.

var resp = JSON.parse(responseBody);
var _ = require('lodash')
pm.test('order by Test', function() {
var expectedSortedOrder = _.orderBy(resp.objects, ['name'],['asc']);
//console.log(expectedSortedOrder);
//console.log(resp.objects);
pm.expect(resp.objects).to.eql(expectedSortedOrder);
});

But I doubt this works for String to check in alphabetical order. This works good for numbers though.

Then you should store the names in an array and then try to sort it.

That leads to the following error

AssertionError: expected [ Array(10) ] to deeply equal [ Array(10) ]

Then do we have any other better way to handle this?