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

时间:2018-07-09 13:20:41

标签: 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>
    );
  }
}

我的测试是这样的:

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
});

该代码的外观如何?

3 个答案:

答案 0 :(得分:4)

我已经更新了静态资源加载方法,请参见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)
})

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

答案 1 :(得分:1)

您要查找的是断言,在这种情况下,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');
});

答案 2 :(得分:0)

我使用这个 cypress 链来等待所有应该为用户加载的图像,而不是更多(不包括不可见或未初始化的图像):

获取所有图像(包括 shadow dom - https://docs.cypress.io/api/commands/get#Arguments

cy.get('img', { includeShadowDom: true })

具有 src 标签(css 选择器 - https://docs.cypress.io/api/commands/filter

.filter('[src]')

并且是可见的(jquery选择器 - https://docs.cypress.io/guides/references/assertions#Chai-jQuery

.filter(':visible')

并且都被加载了(图片加载时设置了“naturalWidth”和“naturalHeight”)

.should(($imgs) => $imgs.map((i, img) => expect(img.naturalWidth).to.be.greaterThan(0)));

多合一:

cy.get('img', { includeShadowDom: true })
        .filter('[src]')
        .filter(':visible')
        .should(($imgs) => $imgs.map((i, /** @type {HTMLImageElement} */ img) => expect(img.naturalWidth).to.be.greaterThan(0)));

感谢这里和其他地方的其他帖子。