Pre-request & Test Scripts
Each request has a Scripts tab with two editors: a pre-request script, run just before the request is sent, and a test script, run after the response arrives. Both are plain JavaScript with access to a small pm object, similar to Postman's sandbox.
pm API
pm.environment.get(key)— read a variable from the active environmentpm.environment.set(key, value)— create or update a variable in the active environmentpm.environment.unset(key)— remove a variablepm.globals.get(key)/pm.globals.set(key, value)/pm.globals.unset(key)— same, but for global variables (always accessible regardless of active environment)pm.iterationData.get(key)— read a column from the attached data file; always returnsundefinedoutside a data-driven run (read-only)pm.response.status/pm.response.statusText— response status (test scripts only)pm.response.headers— response headers object (test scripts only)pm.response.responseTime— elapsed time in ms (test scripts only)pm.response.json()— parse the response body as JSON (test scripts only)pm.response.text()— raw response body as a string (test scripts only)pm.test(name, fn)— register a named test;fnthrowing marks it failedpm.expect(value)— chainable matchers:.toBe(),.toEqual(),.toBeTruthy(),.toBeFalsy(),.toBeDefined(),.toBeNull(),.toContain(),.toHaveProperty(),.toBeGreaterThan(),.toBeLessThan(), plus.notto negate any of them
Example: pre-request script
Set a fresh timestamp on every send:
pm.environment.set('timestamp', Date.now());
Example: test script
Assert on the response and pull a value into an environment variable for later requests:
pm.test('status is 200', () => {
pm.expect(pm.response.status).toBe(200);
});
pm.test('response is not an error', () => {
pm.expect(pm.response.json()).not.toHaveProperty('error');
});
pm.environment.set('userId', pm.response.json().id);
Test results show up in a Tests tab in the response panel, with a pass/fail count badge. Scripts that throw outside of pm.test() (a syntax error, etc.) show up as a single failed test.