测试赛普拉斯中的图像加载

ste*_*ien 2 javascript reactjs 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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我的测试是这样的:

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
});
Run Code Online (Sandbox Code Playgroud)

该代码将如何显示?

小智 29

我已经更新了静态资源加载的配方,请参阅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)
})
Run Code Online (Sandbox Code Playgroud)

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


ses*_*ken 5

您正在寻找的是断言,在这种情况下,这should('be.visible')似乎很合适。https://docs.cypress.io/api/commands/should.html

it("should display a image in element div with class image", () => {
  cy.get('div[class="image"]').find("img").should('be.visible');
});
Run Code Online (Sandbox Code Playgroud)

  • 赛普拉斯的确切行为是什么?404图片仍然是页面上的可见元素(尤其是alt属性) (2认同)