Verify usage of environment variables in Postman request
Preconditions (2)
✅ Expected Result: The request is sent to 'https://jsonplaceholder.typicode.com/posts/1' and the response status code is 200 with a valid JSON body containing post details
pm.test('Status code is 200', () => { pm.response.to.have.status(200); }); const jsonData = pm.response.json(); pm.test('Response has userId', () => { pm.expect(jsonData).to.have.property('userId'); }); pm.test('Response has id', () => { pm.expect(jsonData).to.have.property('id'); }); pm.test('Response has title', () => { pm.expect(jsonData).to.have.property('title'); }); pm.test('Response has body', () => { pm.expect(jsonData).to.have.property('body'); });
This script is written in Postman test tab using pm API.
First, it checks if the response status code is 200, meaning the request was successful.
Then, it parses the response JSON and verifies that the expected fields userId, id, title, and body exist in the response.
Using environment variable {{baseUrl}} in the request URL allows easy switching of target servers without changing the test code.
Now add data-driven testing by running the same request with environment variables for post IDs 1, 2, and 3
token to abc123 in a Postman test script?pm.environment.set(key, value) to set environment variables.pm.variables.set sets local variables, pm.environment.get is for getting values, and pm.setEnvironment is not a valid method.userId after execution?pm.environment.set('userId', 10);
pm.environment.set('userId', Number(pm.environment.get('userId')) + 5);userId to 10.userId (10), adds 5, and sets it back, so userId becomes 15.sessionId but it does not work:pm.environment.delete('sessionId');pm.environment.unset(key) to remove environment variables.pm.environment.delete() is not a valid method, so it does not remove the variable.dev and prod. Which is the best way to use environment variables to switch the base URL without changing the request code?baseUrl variables allows easy switching without code changes.Pass the test and this pattern moves unknown