Cypress - 验证 HTTP 标头响应

Abd*_*ail 6 javascript postman cypress

我收到一个图像形式的 API 响应,目前我需要 2 件事。

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

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

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

  1. 在邮递员中,我可以看到带有图像的响应主体,但是当我在赛普拉斯中运行时,我看到了类似状态代码的验证,那么有没有一种方法可以在浏览器中呈现图像?还可以进行更多验证吗?

Pao*_*olo 4

这里给出了一个例子获取图像的数据 URL,但图像 URL 已过时 - 我替换了 Cypress Github 页面中的图像 URL。

关键是在请求中添加编码

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" />`
  })
})
Run Code Online (Sandbox Code Playgroud)