Test content type, ignoring charset?

I want to test the Content-Type of a response is “text/html”. I thought that type was being returned, but this test kept failing:

    pm.response.to.have.header('Content-Type', 'text/html');

I examined the response closely and I found that the value of the header was actually, “text/html; charset=utf-8”.

For my purposes, the “charset” is unimportant. How can I test the type is correct, regardless of the “charset” value?

Hi.

You could make:

pm.test(“Response has a valid Content-Type header”, function() {
pm.response.to.have.header(“Content-Type”);
pm.expect(pm.response.headers.get(“Content-Type”)).to.include(“text/html”);
});

Or you could store pm.response.headers.get(“Content-Type”) in a var and check with js indexOf

1 Like

Thanks. Looks like a good suggestion. I’ll give it a try.

I wonder: Is the “to.have.header()” test necessary? If the response didn’t have the right header, wouldn’t the following “to.include()” test fail anyway?

PS: A note for other forum readers… When I copied this example and pasted it into Postman, I discovered this forum changes plain quotes ("…") into “pretty” or “smart” quotes (“…”). Copy and paste with caution! (I wonder whether there is a setting to disable those quotes.)

Nobody answered my question, so I’ll make a guess.

The test could be written without to.have.header():

pm.test('Response has a valid Content-Type header', function() {
  pm.expect(pm.response.headers.get('content-type')).to.include('text/html');
});

However, if the response doesn’t have a “Content-Type” header, the test will produce the error, “AssertionError: object tested must be an array, a map, an object, a set, a string, or a weakset, but undefined given”.

That’s not a very easy error message to understand. So, the recommendation is to test specifically for the presence of the header first:

pm.test('Response has a valid Content-Type header', function() {
  pm.response.to.have.header('content-type');
  pm.expect(pm.response.headers.get('content-type')).to.include('text/html');
});

Written this way, if the “Content-Type” header isn’t available, the error message will be, “AssertionError: expected response to have header with key 'content-type'”, which is much easier to understand.

Additionally, I found that include() is not the ideal function to test the header for this value. The function is case-sensitive, but standards say that case is unimportant in MIME types. text/html, Text/HTML, and tExT/HtML are all equivalent. A safer test would use match() instead, with a case-insensitive regular expression:

pm.test('Response has a valid Content-Type header', function() {
  pm.response.to.have.header('content-type');
  // case-insensitive and rooted at the beginning of the string
  pm.expect(pm.response.headers.get('content-type')).match(/^text\/html/i);
});
1 Like