0
0
Postmantesting~15 mins

Timestamp generation in Postman - Build an Automation Script

Choose your learning style9 modes available
Generate and verify current timestamp in Postman
Preconditions (2)
Step 1: Open the Postman request
Step 2: Go to the Pre-request Script tab
Step 3: Add script to generate current timestamp in milliseconds
Step 4: Save the script
Step 5: Send the request
Step 6: Go to the Tests tab
Step 7: Add script to verify the timestamp is a number and is recent
Step 8: Send the request again to run the test
✅ Expected Result: The test passes confirming the timestamp is generated correctly and is a recent number
Automation Requirements - Postman Test Scripts
Assertions Needed:
Timestamp is a number
Timestamp is within 5 seconds of current time
Best Practices:
Use pm.variables.set to store timestamp
Use pm.expect for assertions
Keep scripts simple and readable
Automated Solution
Postman
/* Pre-request Script */
const timestamp = Date.now();
pm.variables.set('currentTimestamp', timestamp);

/* Tests Script */
const timestamp = parseInt(pm.variables.get('currentTimestamp'), 10);
pm.test('Timestamp is a number', () => {
    pm.expect(timestamp).to.be.a('number');
});
pm.test('Timestamp is recent', () => {
    const now = Date.now();
    pm.expect(timestamp).to.be.within(now - 5000, now + 5000);
});

In the Pre-request Script, we generate the current timestamp using Date.now() which returns milliseconds since 1970. We store it in a Postman variable currentTimestamp so it can be accessed later.

In the Tests tab, we retrieve the stored timestamp and convert it to a number. We then check two things: first, that it is a number type, and second, that it is within 5 seconds of the current time to ensure it is recent. This confirms the timestamp generation is working correctly.

We use pm.expect for assertions as recommended in Postman scripts. The code is kept simple and clear for easy understanding and maintenance.

Common Mistakes - 3 Pitfalls
Not storing the timestamp in a variable accessible in Tests tab
Using string comparison instead of numeric comparison for timestamp
Not checking if timestamp is recent
Bonus Challenge

Now add data-driven testing with 3 different time offsets (e.g., current time, 1 minute ago, 1 minute ahead) and verify timestamps accordingly

Show Hint