Checking an image is actually visible in WebDriverJs

I recently discovered a gap in one of my e2e automated tests where I was checking the existence of an uploaded image in the DOM, but not that the image was actually displayed.

[code language=”javascript”]
driver.isElementPresent( By.css( `img[alt=’upload.jpg’]` ) ).then( function( present ) {
assert.equal( present, true, ‘Image not displayed’ );
} );

If the DOM has a reference to the image, but it isn’t actually rendered this test will pass. This isn’t ideal.

I remembered my post about how to check that an image is actually rendered using WebDriver in C# and so I used the same JavaScript script which WebDriverJs sends to the driver:

[code language=”javascript”]
driver.findElement( By.css( `img[alt=’upload.jpg’]` ) ).then( function( element ) {
driver.executeScript( ‘return (typeof arguments[0].naturalWidth!=\"undefined\" && arguments[0].naturalWidth>0)’, element ).then( function( present ) {
assert.equal( present, true, ‘Image not displayed’ );
} );
} );

This works a treat. I’ve moved it into a helper function so I can use this anywhere without repeating it also.

Author: Alister Scott

Alister is a Software Quality Engineer for Automattic.

2 thoughts on “Checking an image is actually visible in WebDriverJs”

  1. Hi Alister.

    Thanks for the blog. Useful stuff :)

    I wasn’t familiar with naturalWidth, and tested if it identifies that an image with “display: none” is not rendered. It still returns its original size, per functional spec. See this fiddle –

    Can you elaborate on the use cases relevant to this solution?


    1. Thanks Eitan. My use case is uploading an image file and the upload failing but the image tag being present: so basically a broken image link.
      I believe yours is the image exists but is hidden by css. I haven’t tried specifically but the WebDriver visibility property of the webelement should detect this.

Comments are closed.