Skip to content
Advertisement

How to compare a string to a date in postman test?

Suppose a API request fetches a users id, email address and birthday. Sample API Request below:

GET: /v1/users HTTP/1.1
Content-Type: application/json
Authorization: bearer {access_token}

For the above request, the following is the response:

{
    "content": [
        {
            "id": 1,
            "email": "random@random.com",
            "birthday": "1990-01-01"
        },
        {
            "id": 40,
            "email": "random1@random1.com",
            "birthday": "1990-18-10"
        }
],
    "last": false,
    "total_elements": 2,
    "total_pages": 1,
    "sort": null,
    "first": true,
    "number_of_elements": 2,
    "size": 20,
    "number": 0
}

Now, what will be the test in postman to make sure that all the returned values under birthday node is greater than 1988-18-01?

I have tried the following:

pm.test("Check birthday greater than 1988-18-01", () => {
    for (i = 0; i < jsonData.content.length; i++) {
        var a = '1988-18-01'; 
        pm.expect(jsonData.content[i].birthday).to.be.above(a);
    }
});

But postman says: “Check birthday greater than 1988-18-01 | AssertionError: expected ‘1990-01-01’ to be a number or a date”.

Advertisement

Answer

So firstly, the dates need to be converted to a format that JS accepts and use the Date constructor to generate the complete date.

Next, the ‘above’ function in pm accepts an integer, so the date format will not be compared. To fix this, we can convert the date to integer format by using the .getTime() function.

Lastly, it’s not a good practice to declare variables inside a for loop. Here’s what you can replace your test with:

pm.test("Check birthday greater than 1988-18-01", () => {

   let date, 
   isoFormatDate,
   a = new Date('1988-01-18').getTime();

   for (i = 0; i < jsonData.content.length; i++) {
    
      date = jsonData.content[i].birthday;
            
      isoFormatDate = new Date(date).getTime(); // Converting to integer from date format
    
      pm.expect(isoFormatDate).to.be.above(a);
   }
});
Advertisement