我想测试 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
});
该代码是什么样的?
最佳答案
我已经更新了静态资源加载的配方,请参阅 https://github.com/cypress-io/cypress-example-recipes/pull/363
要检查图像是否已完成加载,最简单的方法是检查图像的 naturalWidth
或 naturalHeight
属性。
// 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)
})
或者,您可以使用性能条目来确认任何静态资源已完成加载,有关详细信息,请参阅上面的拉取请求。
关于javascript - 在 Cypress 中测试图像加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51246606/