How to get the date/time of response in Postman?

Viewed 489

I am testing this public API using postman.

When I send a request to this endpoint:

POST: https://reqres.in/api/users

with the following request body:

{
    "name": "Rose Thompson",
    "job": "Senior Markets Agent"
}

I get this as a response:

{
    "name": "Rose Thompson",
    "job": "Senior Markets Agent",
    "id": "818",
    "createdAt": "2022-05-09T09:30:43.839Z"
}

Then I am writing some custom API tests to make sure that the actual and expected responses are the same.

Here is my test code in Postman:

pm.test("Successful POST request", function () {
    pm.expect(pm.response.code).to.be.oneOf([201, 202]);
});

const response = pm.response.json();

pm.test("Should Have Right Name", () => {
    const actual = response.name;
    const expected = "Rose Thompson";

    pm.expect(actual).to.eq(expected);
})

pm.test("Should Have Right Job", () => {
    const actual = response.job;
    const expected = "Senior Markets Agent";

    pm.expect(actual).to.eq(expected);
})

Now I want to write a test for the createdAt field from the response body. I know how to get the actual value from the response itself (I'll do it like this response.createdAt), however, I am having difficulties getting the expected value of the createdAt field.

Can you please tell me how can I get the expected value of the createdAt field?

1 Answers

I would test for this field being present, and not null. If you really want to validate the actual date/time, I would try to avoid the time part, and test for the date.

pm.test("Validate createdAt is present", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData.createdAt).not.to.be.null;
});

pm.test("Validate createdAt Date", function () {
    const jsonData = pm.response.json();
    const createdAt = jsonData.createdAt;
    const Today = new Date();
    const TodayISO = Today.toISOString().split('T')[0]
    
    // Compare createdAt format for date (substring first 10 characters?)
    pm.expect(createdAt.substr(0,10)).to.equal(TodayISO);
});

The issue here is based on timing. If your tests are running continuously, it is possible for the request/response, and the machine running the tests to cross the date boundary, so the date of the request is technically yesterday when the test codes runs.

Similar to Lucas Nguyen's comment, I would try to avoid testing the actual date if possible, and simply check the field is provided, and not null.

Related