在 Cypress 中测试图像加载

新手上路,请多包涵

我想测试 Cypress 是否将图像加载到页面中。

我的源代码如下所示:

 import React from "react";

export default class Product extends React.Component {
  render() {
    return (
      <div className="item">
        <div className="image">
          <img src="../images/Banana-Snowboard.png" alt="Snow Board" />
        </div>
        <div className="middel aligned content">
          <div className="description">
            <a>Snow Board</a>
            <p>Cool Snow Board</p>
          </div>
          <div className="extra">
            <span>Submitted by:</span>
            <img
              className="ui avatar image"
              src="./images/avatar.png"
              alt="Avatar"
            />
          </div>
        </div>
      </div>
    );
  }
}

我的测试是这样的:

 it("should display a image in element div with class image", () => {
  cy.get('div[class="image"]').find("img"); // some code that test that image is loaded so that it is displaye on the web page
});

it("shoul diplay a image in element div with class image inside class extra", () => {
  cy.get('div[class="extra"]').find('img[class="ui avatar image"]');
  //some code that check that image is loaded so that it is display the web page
});

该代码将如何显示?

原文由 stein korsveien 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 601
1 个回答

我已经更新了静态资源加载的方法,请参阅 https://github.com/cypress-io/cypress-example-recipes/pull/363

要检查图像是否已完成加载,最简单的方法是检查图像的 naturalWidthnaturalHeight 属性。

 // we can wait for the <img> element to appear
// but the image has not been loaded yet.
cy.get('[alt="delayed image"]')
.should('be.visible')
.and(($img) => {
  // "naturalWidth" and "naturalHeight" are set when the image loads
  expect($img[0].naturalWidth).to.be.greaterThan(0)
})

或者,您可以使用性能条目来确认任何静态资源已完成加载,有关详细信息,请参阅上面的拉取请求。

原文由 gleb bahmutov 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题