0

I have a short protractor-based test of a login page. I would like to test that the 'banner' image is at least plausibly correct (e.g., that its not a broken link). Following a similar question (How to validate if the image is display in the table using webdriver) I checked the naturalWidth property of the img element.

While this approach seems to work (the naturalWidth is 0 if there was an error loading the image, but non-zero normally) with PNG images, and works okay in Chrome with an SVG image, in Firefox the naturalWidth property of the img element is always zero for any of my .svg images. Is there some other way to programmatically determine if an image loaded correctly/completely?

Here is what the HTML looks like:

<img src="/static/img/logo.svg" style="width:300px">

And here is what the JavaScript console in Firefox says about the img:

a[0].src
"http://localhost:1080/static/img/logo.svg"
a[0].naturalWidth
0
a[0].width
300

Sadly, if I break the link, by changing the HTML to:

<img src="/static/img/INVALID.svg" style="width:300px">

I get the exact same result at the JavaScript console.

Community
  • 1
  • 1
P.T.
  • 24,557
  • 7
  • 64
  • 95

2 Answers2

2

Wait for either an onload or onerror event to fire. If onload fires then the image is loaded and you can run your test, if onerror fires it failed to load.

Here's an onerror example.

<img src="http://localhost/serverGone.gif" onerror="alert('serverGone')">

The use of alert is an example, you can do whatever you want, and you can add them dynamically using setAttribute or addEventListener

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
  • While I'm willing to change the server implementation to track this down, it seemed a bit invasive to add onerror handlers (certainly alerts are bit more invasive than I want). But just setting `onerror="this.failed=true"` was sufficient to set a property on the img that my protractor tests could get at. Seems like a good idea for my app to notice and report failed img loads anyway, so I'll probably expand this a bit, too. Thanks! – P.T. Feb 04 '15 at 06:55
1

Our Webdriver code is in Java, and we set up a separate utility class (using HttpURLConnection) to get us the status codes from the http request. I wonder if you could do something similar in .js using something like the approach shown in the answer to this question

Community
  • 1
  • 1
weems74
  • 310
  • 2
  • 5
  • Refetching the source to check the result would help for cases where the images don't exist, but wouldn't detect problems where the result wasn't an image (or was a corrupt image or whatnot). I'd like to be as close to detecting if the image is showing up correctly or not as I can. – P.T. Feb 04 '15 at 06:58