繁体   English   中英

赛普拉斯 - 等待 API 响应并验证 UI 更改

[英]Cypress - wait for the API response and verify UI changes

我有一个组件,我想用一些 e2e 测试来介绍它。 该组件在输入中获取用户提供的URL,单击按钮后调用API,然后返回该URL的缩短版本。 之后,将缩短的 url 添加到 UI 输入下方的列表中,并进行一些 localStorage 断言。 我希望赛普拉斯等待 API 响应,然后才检查 UI 是否添加了列表项。 我做了这个工作,但我在wait()方法中硬编码了等待时间。 我如何以编程方式实现这一目标?

describe("Shortener component", () => {
  it("Should add the list item and data to localStorage", () => {
    cy.visit("http://127.0.0.1:5500"); //Live server extension address

    cy.get("#url-input").type("https://facebook.com");
    cy.get("#form-submit-button").click();

    // wait for the api response and make sure that the value has been added to the localStorage
    cy.wait(40000); //todo - wait for the api response instead of hardcoding the wait time
    const localStorageData = localStorage.getItem("linksData");
    if (JSON.parse(localStorageData)) {
      expect(JSON.parse(localStorageData)[0].inputValue).to.eq(
        "https://facebook.com"
      );
    }

    // check if the new list item with the corrct value has been addded
    cy.get(".shortener-component__list-item")
      .contains("https://facebook.com")
      .should("be.visible");

    //validation mesasge should not be visible
    cy.get("#validationMesage")
      .contains("Please add a valid link")
      .should("not.be.visible");
  });
});

我尝试使用intercept() ,但失败了。 不知道如何使它工作。 我也看到了一些类似的 SE 主题,但这对我没有帮助。

任何想法/例子apreciated:)

谢谢 !

文档中有示例,只需要一些阅读和实验。

通常,您需要三个命令: cy.intercept().as()cy.wait()

cy.intercept(your_url).as('getShortenedUrl');
cy.wait('@getShortenedUrl');

你也可以使用.then()来访问拦截 object,例如响应:

cy.wait('@getShortenedUrl').then(interception => { });

或者您可以使用.its()检查响应中的某些内容:

cy.wait('@getShortenedUrl').its('response.statusCode').should('eq', 200);

关键是在cy.wait('@getShortenedUrl')之后,已经收到响应。

根据您给出的事件顺序

  1. 短 URL 返回
  2. 添加到本地存储
  3. 添加到列表

只需更改功能测试的顺序

  1. 测试列表 - 这是最后一个事件,但有可重试的命令(您可以增加超时)
  2. 现在测试 localStorage,如果 UI 有短 URL 那么 localStorage
cy.contains('.shortener-component__list-item', 'https://facebook.com', { timeout: 40000 })
  .then(() => {

    // nested inside .then() so that the above passes first

    const localStorageData = localStorage.getItem("linksData");
    const linksData = JSON.parse(localStorageData);
    expect(linksData).not.to.eq(undefined);
    expect(linksData[0].inputValue).to.eq("https://facebook.com");
  })

或者,要在 localStorage 检查中使用重试和超时,

cy.wrap(localStorage.getItem("linksData"))
  .should('not.eq', undefined, { timeout: 40000 }) // will retry the above until true
  .then(data => JSON.parse(data))
  .should(parsedData => {              
    expect(parsedData.inputValue).to.eq("https://facebook.com");
  });

我想你也应该开始测试

cy.clearLocalStorage("linksData")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM