0
0
Postmantesting~15 mins

Header assertions in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify response headers for a GET request
Preconditions (2)
Step 1: Send a GET request to https://jsonplaceholder.typicode.com/posts/1
Step 2: Check the response headers for 'Content-Type'
Step 3: Check the response headers for 'Cache-Control'
Step 4: Check the response headers for 'Content-Encoding'
✅ Expected Result: The response headers contain 'Content-Type' with value 'application/json; charset=utf-8', 'Cache-Control' with a non-empty value, and 'Content-Encoding' header is present
Automation Requirements - Postman Tests (JavaScript)
Assertions Needed:
Assert 'Content-Type' header equals 'application/json; charset=utf-8'
Assert 'Cache-Control' header is present and not empty
Assert 'Content-Encoding' header is present
Best Practices:
Use pm.response.headers.get() to access headers
Use strict equality for header value assertions
Write clear and descriptive assertion messages
Automated Solution
Postman
pm.test('Content-Type header is application/json; charset=utf-8', () => {
    const contentType = pm.response.headers.get('Content-Type');
    pm.expect(contentType).to.eql('application/json; charset=utf-8');
});

pm.test('Cache-Control header is present and not empty', () => {
    const cacheControl = pm.response.headers.get('Cache-Control');
    pm.expect(cacheControl).to.be.a('string').and.not.empty;
});

pm.test('Content-Encoding header is present', () => {
    const contentEncoding = pm.response.headers.get('Content-Encoding');
    pm.expect(contentEncoding).to.not.be.undefined;
});

This test script uses Postman’s built-in pm object to access response headers and make assertions.

First, it checks that the Content-Type header exactly matches the expected string using pm.expect().to.eql().

Next, it verifies that the Cache-Control header exists and is not empty by checking its type and length.

Finally, it confirms the presence of the Content-Encoding header by asserting it is not undefined.

Each test has a clear name describing what it checks, making it easy to understand test results.

Common Mistakes - 3 Pitfalls
{'mistake': "Using pm.response.headers['Content-Type'] instead of pm.response.headers.get('Content-Type')", 'why_bad': 'pm.response.headers is not a plain object, so direct property access returns undefined.', 'correct_approach': "Use pm.response.headers.get('Header-Name') to reliably get header values."}
Using loose equality (==) instead of strict equality (=== or .eql()) for header value checks
Not checking if header exists before asserting its value
Bonus Challenge

Now add tests to verify headers for three different API endpoints with different expected header values.

Show Hint