0
0
Postmantesting~10 mins

Token management in variables in Postman - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test automates the process of obtaining an authentication token from an API and storing it in a Postman environment variable. It then verifies that the token is correctly saved for use in subsequent requests.

Test Code - Postman Tests
Postman
pm.test("Get Auth Token and save to environment variable", function () {
    pm.sendRequest({
        url: pm.environment.get("auth_url"),
        method: 'POST',
        header: {
            'Content-Type': 'application/json'
        },
        body: {
            mode: 'raw',
            raw: JSON.stringify({
                username: pm.environment.get("username"),
                password: pm.environment.get("password")
            })
        }
    }, function (err, res) {
        pm.expect(err).to.equal(null);
        pm.expect(res).to.have.property('code', 200);
        const jsonData = res.json();
        pm.expect(jsonData).to.have.property('token');
        pm.environment.set("auth_token", jsonData.token);
        pm.expect(pm.environment.get("auth_token")).to.be.a('string').and.not.empty;
    });
});
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1Test starts and sends POST request to authentication URL with username and password from environment variablesPostman sends HTTP POST request to the API endpoint defined in 'auth_url' environment variable with JSON body containing username and password-PASS
2Receives response from APIAPI responds with HTTP status code 200 and JSON body containing a 'token' fieldCheck that error is null and response code is 200PASS
3Parse JSON response and verify 'token' field existsResponse JSON parsed successfully and contains 'token' keyAssert that 'token' property exists in response JSONPASS
4Save the token value to environment variable 'auth_token'Environment variable 'auth_token' is set with the token stringVerify 'auth_token' environment variable is a non-empty stringPASS
Failure Scenario
Failing Condition: API returns error or no token in response, or environment variable fails to set
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify immediately after receiving the API response?
AThat the response status code is 200 and there is no error
BThat the token is saved in local storage
CThat the username and password are correct
DThat the environment variable 'auth_url' is set
Key Result
Always verify that tokens received from authentication APIs are correctly saved in environment variables for reuse in subsequent API calls. This ensures smooth and secure token management in automated tests.