let moment = require ('moment');
pm.test("Date is present in correct format", function () {
pm.expect(jsonData.data.date).to.include(moment().format('DD-MM-YYYY hh:mm:ss'));
});
However, whenever I run the test though the format returns correctly, I’m faced with the fact the seconds in the date/time different by 2 to 3 seconds and the test fails. I thought I was just asking for the format but it appears not. Does anyone know how I can just validate the date format regardless of what time the test ran or even was delayed by?
If you’re just wanting to check that the format is correct, you could use the chai .match() function. This takes regular expressions so you will be able to add something to match this pattern.
let jsonData = pm.response.json();
pm.test("Date is present in correct format", function () {
pm.expect(jsonData.data.date).to.match(/^\d{2}-\d{2}-\d{4}\s\d{2}:\d{2}:\d{2}$/);
});
Thank you this works when the separator is a - however this seems to fail of the date separator is /
thus checking a format for dd/mm/yyyy hh:mm:ss fails
Your pretty close with your first try. I recommend using moments isValid() function. https://momentjs.com/docs/
moment(date, format, locale, strict).isValid() will return a boolean. locale and strictness are optional, in this case you want to strict to verify the date is exact.
for (i = 0; i < jsonData.length; i++) {
pm.test("Date is present in correct format", function () {
pm.expect(jsonData[i].endDateTime).to.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}:\d{1}$/);
});
}
This site mentioned above is really helpful especially with the reference bar on the right menu to understand what expressions can be used plus now the debugger of the regex is an amazing feature. Highly recommend it. Thanks @danny-dainton for sharing this.