Abdulla Suhail
Abdulla Suhail

Reputation: 78

Cypress - Validating HTTP Header Response

I am getting a API response as an image, currently i need 2 things.

  1. On postman i am validating the response in Tests as below .

    pm.test("Content-Type is present", function () { pm.response.to.have.header("Content-Type","image/png"); });

I want to know how the header response be validated in Cypress code after i have the response.

  1. In postman i can see the response body having a image, but when i run in Cypress all i see the validation like status code,so is there a way that the image can be rendered in browser ? and more validations can be done ?

Upvotes: 6

Views: 5785

Answers (2)

Paolo
Paolo

Reputation: 5441

An example is given here Get Data URL of an image, but the image url is out of date - I substituted the one from Cypress Github page.

Key is to add encoding to the request

cy.request({
  url: 'https://cloud.githubusercontent.com/assets/1268976/20607953/d7ae489c-b24a-11e6-9cc4-91c6c74c5e88.png',
  encoding: 'base64',
}).then((response) => {

  // test any response properties here

  const base64Content = response.body
  const mime = response.headers['content-type'] // or 'image/png'
  expect(mime).to.eq('image/png')

  // see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  const imageDataUrl = `data:${mime};base64,${base64Content}`
  return imageDataUrl
})
.then((imageDataUrl) => {

  // display the image in Cypress test runner

  cy.window().its('document.body')
  .then($body => {
    $body[0].innerHTML = `<img src="${imageDataUrl}"  height="100" width="300" />`
  })
})

Upvotes: 4

Alapan Das
Alapan Das

Reputation: 18650

You can use cy.request to validate the response headers -

cy.request('GET', 'https://jsonplaceholder.cypress.io/comments').then((response) => {
  expect(response.headers).to.have.property('Content-Type', 'image/png') //assert Request header
})

Upvotes: 1

Related Questions