Cypress - 验证 HTTP Header 响应

Cypress - Validating HTTP Header Response

我收到 API 响应作为图像,目前我需要 2 个东西。

  1. 在邮递员上,我正在验证测试中的响应,如下所示。

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

我想知道 header 收到响应后如何在 Cypress 代码中验证响应。

  1. 在 postman 中我可以看到响应 body 有一个图像,但是当我在 Cypress 中 运行 我看到像状态代码这样的验证,所以有没有办法可以将图像在浏览器中呈现?并且可以进行更多验证?

您可以使用 cy.request 来验证响应 headers -

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

这里给出了一个例子 Get Data URL of an image,但是图像 url 已经过时了 - 我用 Cypress Github 页面中的图像进行了替换。

关键是在请求中添加编码

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" />`
  })
})