Don’t live with broken images


This is a simple example application with a Mocha test that finds all broken images on a page using the jQuery.waitforimages plugin.

So, have you ever discovered that there’s a broken image on your web application? Maybe it’s on a page that is seldom visited by developers. You’ve got great mocha tests for your UI features, but none of them can catch broken images?

I was in a situation like this a while ago. Not anymore!

Now I can write tests like this:

describe('Front page', function() {

  it ('Shows image of Larry Wall', function() {


And get test reports like this:


The checkAllImages call right there generates a test case that checks that all <img> tags are successfully loaded. It also verifies my CSS backgrounds!

The example application

To run my example on OSX, you need to install Bower, clonethis repo, cd into it and then

bower install
open http://localhost:8000/test/

Now that you’ve got the tests running in your browser, you might as well try to break them. So, edit index.css so that the background URL is incorrect, and then reload. You’ll find that a test case just broke.

Steps to success – Here’s how to do it for your application

    1. Add nasty stuff to your application

The assumption is that you’re using a setup similar to mine. That is, you’re using Mocha for your tests and you’re running your actual application in an <iframe>. My setup with the tests and all is in this test.js file.

Here’s the thing you don’t want to hear: you have to add some extra code to your actual application. In other words, you need to include the jquery.waitforimages plugin and a custom function that uses the plugin to produce the list of broken images on the page. It can be found here.

I tried to make this work by adding the plugin to my test code but I didn’t succeed, because the paths went wrong and the plugin didn’t work. So, it seems you need to include the plugin in your production code. But of course, you can do some iffing in your app to include the test-specific code only in case the app is not running in an <iframe>, right?

    1. Define a test helper

For your Mocha tests, you can define a helper function checkAllImages. It will generate a test case that checks that all images are valid in the application iframe. I’ve defined mine in test.js.

    1. Call the helper in relevant test cases

Like in test.js.

  1. Profit

No more broken images in production. You win.


Never miss a post