Cover image

Image Snapshot Testing with Mocha

Mar 9, 2021

Snapshot testing is a testing mechanism that for long has seemed to be exclusive to Jest. The main idea is to generate expected values into a separate file and to compare the actual tested values with these saved values. It is also possible to update snapshots by passing an environment variable. This testing approach is great for complex data like large strings, DOM content, or images. I wrote a package to use image snapshot testing also with Mocha.

Snapshot testing with Jest

Snapshot testing itself is a built-in feature of Jest, and when searching specifically for image snapshots, you'll quickly find jest-image-snapshot, which does great work comparing and updating image snapshots. It also provides convenience features like a base64 diff output, which allows us to view the diff from a CI environment (since the diff image file cannot be saved or viewed).

What about Mocha?

While this is all great, what if I'm not using Jest for whatever reason? What if I'm using Mocha?

For simple snapshot testing, there are some options. For Chai users, there is mocha-chai-snapshot. For expect users, there is expect-mocha-snapshot. It basically wraps the jest snapshot logic by injecting an artificial testing context. Big credit to Alexander Beletsky here!

What was still missing was a package that ports image snapshot testing to Mocha. Since I'm currently using expect as an assertion library, I focused on finding a solution for this one.

I started to fiddle around with jest-image-snapshot in combination with expect-mocha-snapshot, and it turned out to be way easier than expected to make it Mocha compatible. I put it into its own NPM package, called expect-mocha-image-snapshot. Usage is pretty similar to Jest, you only have to pass the testing context via this. Here is a quick code sample:

import expect from 'expect'
import { toMatchImageSnapshot } from 'expect-mocha-image-snapshot'

expect.extend({ toMatchImageSnapshot })

it('works', async function () {
  const screenshot = await puppeteer.screenshot()

You can have a look at the code in case you are interested in how it works. It is pretty straight-forward.


That was my guide to image snapshot testing with Mocha. If you like expect-mocha-image-snapshot, you can support me by putting a star on GitHub. Also, let me know what you think about it.

If you like what I'm doing, follow me on Twitter or check out my website. Also consider donating at Buy Me a Coffee, PayPal or Patreon. Thank you so much! ❤️

Subscribe via RSS