javascript - Cypress - 等待 API 响应并验证 UI 更改

标签 javascript cypress

我有一个组件,我想用一些 e2e 测试来覆盖它。该组件采用用户在输入中提供的 URL,在单击按钮后调用 API,然后返回该 URL 的缩短版本。之后,缩短的 url 被添加到 UI 输入下方的列表中,并进行一些 localStorage 断言。我希望 Cypress 等待 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 :)
谢谢 !

最佳答案

根据您提供的事件顺序

  • 返回的短 URL
  • 添加到 localStorage
  • 添加到列表

  • 只需更改功能测试的顺序
  • 测试列表 - 这是最后一个事件,但具有可重试的命令(您可以增加超时)
  • 现在测试 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")
    

    关于javascript - Cypress - 等待 API 响应并验证 UI 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67355454/

    相关文章:

    javascript - Mongoose .findOne 错误返回找到的模型?

    javascript - 如何使用 jQuery 更改图像源并以一些不错的效果加载它

    javascript - 在 React 和 JSX 中反转 if 语句

    javascript - JS 中函数的原型(prototype)?

    java - 可以从applet调用servlet

    console - Cypress 运行命令而无需重新运行测试

    javascript - 如何在 Cypress 更新夹具文件

    javascript - 使用 before 钩子(Hook)时 cy.get() 找不到注册的别名

    automation - 在多个 URL 中执行 CypressIO 测试

    javascript - Cypress 打字错误 - 文本区域中的输入困惑