Search code examples
angularjsselenium-webdriverjasmineprotractorend-to-end

Protractor: More specific feedback to User?


Say I have a page of 10 images and the 3rd and 5th don't load. How can I say something like:

2/5 images didn't load.

Or "image2.jpeg" and image5.jpeg" hasn't loaded.

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

});

Solution

  • I would switch to Protractor-specific functionality here - using filter() to filter out the broken images, then, using map() to get an array of src values and then using Jasmine's fail() to fail with a desired error message:

    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(","));              
            })
            }
        });
    });