Verify response headers for a GET request
Preconditions (2)
✅ 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
Jump into concepts and practice - no test required
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.
Now add tests to verify headers for three different API endpoints with different expected header values.
pm.response.to.have.header('Content-Type') check for?pm.response.to.have.header() is used to check response headers.pm.expect(pm.response.headers.get('Header-Name')).to.eql('value') to check header value.headers.get() and assertion to.eql(). Others have syntax errors or incorrect usage.pm.test('Check Server header', () => {
pm.expect(pm.response.headers.get('Server')).to.equal('nginx');
});pm.test('Check Content-Length', () => {
pm.expect(pm.response.headers.get('Content-Length')).to.be('1234');
});to.be is not a valid Chai assertion method for value equality in Postman.to.equal or to.eql to compare values correctly.to.be is not a valid assertion method; it should be to.equal or to.eql. -> Option CNumber() to convert the header string value to a number for comparison.pm.expect(val).to.be.above(1000) to check if the number is greater than 1000.