假设我有10张图片的页面,第3张和第5张没有加载。我怎么能这样说:
2/5张图片无法加载。
或" image2.jpeg"和image5.jpeg"还没有加载。
browser.waitForAngularEnabled(false);
it('should find all images', function () {
browser.get('https://popeyes.com/');
var imagesBrokenCount = browser.executeScript(`
var elms = document.querySelectorAll("img");
return [].filter.call(elms, e => e.offsetHeight > 1 && e.naturalHeight <= 1).length;
`);
browser.sleep(1000);
expect(imagesBrokenCount).toEqual(0);
});
答案 0 :(得分:1)
我会在此处切换到特定于Protractor的功能 - 使用filter()
过滤掉损坏的图像,然后使用map()
获取src
值数组,然后使用Jasmine&# 39; s fail()
失败并显示所需的错误消息:
it('should find all images', function () {
browser.get('https://www.popeyes.com');
var brokenImages = $$("img").filter(function (img) {
return img.getAttribute("offsetHeight").then(function (offsetHeight) {
return img.getAttribute("naturalHeight").then(function (naturalHeight) {
return offsetHeight > 1 && naturalHeight <= 1;
});
});
});
brokenImages.count().then(function (countBrokenImages) {
if (countBrokenImages > 0) {
console.log(countBrokenImages + " images loaded successfully");
brokenImages.map(function (img) {
return img.getAttribute("src");
}).then(function (sources) {
fail("Failed to load the following images: " + sources.join(","));
})
}
});
});
答案 1 :(得分:1)
您只需从损坏的图像中返回源,然后断言返回的数组为空:
browser.get('https://popeyes.com/');
var brokenImages = browser.executeScript(`
return [].slice.call(document.querySelectorAll("img"))
.filter(e => e.offsetHeight > 1 && e.naturalHeight < 1)
.map(e => e.src);
`);
browser.sleep(1000);
expect(brokenImages).toBeEmptyArray();