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.

4 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”: “[email protected]”,
“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?