Chai error: Is there support for moment.js date compare features?

I am checking to see if a date that is returned via my request is the same or after a date that is stored in my collection variables. I would like to use moment.js to do this because it looks like a really clean way to get what I want – it has just the comparison I’m looking for: isSameOrAfter (https://momentjs.com/docs/#/query/is-same-or-after/). However, when I attempt to use this, or even the more basic “isAfter”, I get “Error: Invalid Chai property: isAfter”.

As far as I can tell, this should be supported. Postman documentation (https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference/) says it supports moment 2.22.2 and isAfter is tagged as moment 2.0.0. Am I reading this wrong?

I tried out a of couple of the other moment features, like .add and it worked fine. I finally winnowed my code down to a very basic test:

const moment = require("moment")
var jsonData = pm.response.json().results
//let updated_since = moment(jsonData.updatedAt).format("YYYY-MM-DD")
//let us_var = moment(pm.collectionVariables.get("updatedSince")).format("YYYY-MM-DD")

if(jsonData.length > 0) {
    (pm.test("Response data is filtered by updatedSince", () => {
        var size = jsonData.length
        for(var i = 0; i < size; i++) {
            pm.expect(moment("2020-06-06")).isAfter(moment("2020-05-20"))
        }
    },
    pm.environment.set("x-next-token", null)
))}

Still getting the Chai error with the above. I guess I’ll pursue ways outside of moment.js to do this, but I’m disappointed. Please let me know if there is something basic I’m missing here. I’m relatively new to coding.

Hey @jshafer

Welcome to the community!! :star:

This looks like it’s to do with the way that you are writing your pm.expect statements.

The moment syntax that you’re using returns true/false, you can see this if you log the result to the console:

const moment = require("moment")

console.log(moment("2020-06-06").isAfter(moment("2020-05-20")))

In order to use this in a test, you would need to write the test like this:

pm.test('testing', () => {
    pm.expect(moment("2020-04-06").isAfter(moment("2020-05-20"))).to.be.true
}) 

This is putting the whole moment statement inside the pm.expect() function and then using the chained getters, write the assertion.

Just something to remember when using chai assertions, the first getter to start the chained assertion needs to be .to after the pm.expect() statement - For example pm.expect(1).to.eql(1)

Wonderful! That works. Thank you so much. Great tip on the .to after Chai assertions.

1 Like