gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:03:24 24 4
gpt4 key购买 nike

我有一个组件,我想用一些 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com