【问题标题】:Cypress - Validating HTTP Header ResponseCypress - 验证 HTTP 标头响应
【发布时间】:2021-11-01 12:40:12
【问题描述】:

我正在以图像形式获得 API 响应,目前我需要两件事。

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

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

我想知道收到响应后如何在赛普拉斯代码中验证标头响应。

  1. 在邮递员中,我可以看到响应正文包含图像,但是当我在赛普拉斯中运行时,我看到的都是状态码等验证,那么有没有办法可以在浏览器中呈现图像?还可以进行更多验证吗?

【问题讨论】:

  • 对于第 2 点,我需要查看您的回复正文。
  • 响应正文只是一个图像,我可以通过使用编码在浏览器上呈现它。我还可以下载它以比较图像以进行进一步验证。

标签: javascript postman cypress


【解决方案1】:

这里给出了一个示例Get Data URL of an image,但图片网址已过时 - 我替换了赛普拉斯 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" />`
  })
})

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多