Test Overview
This test checks that a Postman pre-request script correctly prepares data before sending an API request. It verifies that the data is set in the environment and used in the request body.
This test checks that a Postman pre-request script correctly prepares data before sending an API request. It verifies that the data is set in the environment and used in the request body.
pm.test("Pre-request script sets data correctly", () => { // Run the pre-request script manually pm.environment.set('userId', '12345'); // Simulate sending a request using the prepared data const requestBody = { id: pm.environment.get('userId'), name: 'Test User' }; // Assert the userId is set correctly pm.expect(pm.environment.get('userId')).to.eql('12345'); // Assert the request body uses the prepared data pm.expect(requestBody.id).to.eql('12345'); });
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | Postman environment is clean with no userId set | — | PASS |
| 2 | Pre-request script sets environment variable 'userId' to '12345' | Environment variable 'userId' is now '12345' | Check environment variable 'userId' equals '12345' | PASS |
| 3 | Prepare request body using environment variable 'userId' | Request body contains { id: '12345', name: 'Test User' } | Verify requestBody.id equals '12345' | PASS |
| 4 | Assertions verify environment variable and request body data | Assertions pass confirming data preparation | pm.expect(pm.environment.get('userId')).to.eql('12345') and pm.expect(requestBody.id).to.eql('12345') | PASS |
token in a pre-request script?pm.variables.set or pm.environment.set is used to set variables. Here, pm.variables.set('token', 'abc123'); correctly sets the variable.pm.environment.get and pm.variables.get retrieve variables, not set them. pm.environment.delete removes variables.timestamp after running this pre-request script?const now = new Date().getTime();
pm.variables.set('timestamp', now);new Date().getTime()timestamp to this number using pm.variables.set, which is correct syntax.pm.environment.set('authToken', getToken());
function getToken() {
return getToken();
}getToken() inside pm.environment.set('authToken', getToken()). The function getToken() returns getToken(), which calls itself again.getToken() calls itself directly, leading to a stack overflow.userId. Which pre-request script correctly achieves this?Math.floor(Math.random() * 1000) generates a random whole number between 0 and 999, suitable for a user ID.pm.environment.set('userId', id); correctly stores the generated ID in the environment variable userId.Pass the test and this pattern moves unknown