开发者问题收集

在 Cypress 测试中模拟 imgur 请求/响应

2020-04-27
693

我正在尝试存根 imgur 请求和响应。根据 API 文档 ,我可以发出如下匿名请求:

curl --location --request POST 'https://api.imgur.com/3/image' \
--header 'Authorization: Client-ID {{clientId}}' \
--form 'image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'

响应如下(我已为其创建了一个装置,即 navbar-logo-image.json

{
  "data": {
    "id": "orunSTu",
    "title": null,
    "description": null,
    "datetime": 1587998106,
    "type": "image/png",
    "animated": false,
    "width": 2100,
    "height": 1709,
    "size": 138557,
    "views": 0,
    "bandwidth": 0,
    "vote": null,
    "favorite": false,
    "nsfw": null,
    "section": null,
    "account_url": null,
    "account_id": 0,
    "is_ad": false,
    "in_most_viral": false,
    "tags": [],
    "ad_type": 0,
    "ad_url": "",
    "in_gallery": false,
    "deletehash": "N9YaI4CIkq3rIar",
    "name": "",
    "link": "https://i.imgur.com/12gZbNU.png"
  },
  "success": true,
  "status": 200
}

我的测试场景如下:

it('should allow the user to select a navbar component and replace a logo', () => {
  cy.server();
  cy.route({
    url: '/3/image',
    method: 'POST',
    response: "fixture:navbar-logo-image.json",
  }).as('imgurRequest');
  cy.getIframeBody('builder-showcase').find('[data-cy="navbar-component"]').eq(0).click();
  cy.getIframeBody('builder-showcase').find('[data-cy="navbar-logo-image"]').eq(0).click();
  cy.get('[data-cy="builder-sidebar-menu-select-image-navbar"]').eq(0).click();
  const navbarLogoImage = 'images/navbar-logo-image.png';
  cy.get('[data-cy="image-file-input"]').attachFile(navbarLogoImage);
  cy.get('[data-cy="image-alt-text"]')
    .clear()
    .type('Twitter logo image');
  cy.get('.source-image').invoke('attr', 'src')
    .then(uploadedLogoImage => {
      expect(uploadedLogoImage).to.contain('iVBORw0KGgoAAAANSUhEUgAACDQAAAatCAYAAAAmAogfAAAgAElEQVR4XuzdC5icdXn38');
    });
  cy.get('[data-cy=image-select-save]').click();
});

API 调用在此行触发 cy.get('[data-cy=image-select-save]').click(); 。我想拦截它并将帖子发布到虚拟 API,然后提供虚拟响应。我该怎么做?

1个回答

如果 cy.request() 中的参数正确,则您已设置为拦截调用并模拟对 json 装置的响应。然后,您可以使用 cy.wait() 获取包含请求和响应的 http 对象:

cy.get('[data-cy=image-select-save]').click();
cy.wait('@imgurRequest').then(xhr => {
    // do something with the xhr object
});

确保您的请求不是 fetch 类型,因为 cypress 尚无法捕获 fetch 请求。另外,我建议在 cy.request() 中的 url 参数中使用 glob 模式,例如 url: '*/3/image'

PeaceAndQuiet
2020-04-27