Introduction
Pre-request scripts run before sending a request to set up or change data. This helps tests use fresh or correct information every time.
Jump into concepts and practice - no test required
Pre-request scripts run before sending a request to set up or change data. This helps tests use fresh or correct information every time.
pm.environment.set('variable_key', 'value'); // or pm.variables.set('variable_key', 'value'); // You can also write JavaScript code here to prepare data
authToken with a fixed value.pm.environment.set('authToken', '12345abcde');
const timestamp = new Date().toISOString(); pm.environment.set('currentTime', timestamp);
const randomId = Math.floor(Math.random() * 1000); pm.environment.set('randomUserId', randomId);
This pre-request script creates a random token and saves it as authToken. The test checks that the token exists and is a string longer than 5 characters.
// Pre-request script const token = 'token_' + Math.random().toString(36).substring(2, 10); pm.environment.set('authToken', token); // Request header uses {{authToken}} variable // Test script pm.test('Auth token is set', function () { const tokenValue = pm.environment.get('authToken'); pm.expect(tokenValue).to.be.a('string').and.to.have.lengthOf.above(5); });
Pre-request scripts help keep your tests flexible and up-to-date by preparing data just before sending requests.
Always check that variables set in pre-request scripts are correctly used in your requests and tests.
Pre-request scripts run before requests to prepare or update data.
They use JavaScript to set variables like tokens, timestamps, or random values.
This makes tests more reliable and dynamic.
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.