Mocha Snapshot Testing Utility

7.9.10 · maintenance · verified Sun Apr 19

snap-shot-it is a snapshot testing utility designed for Mocha and other BDD-style JavaScript test runners. It provides a robust mechanism to capture the output of functions or data structures during test execution and compare them against previously saved snapshots, making it easier to track unintended changes. The current stable version is 7.9.10, released in late 2022, and its release cadence primarily focuses on dependency updates and minor bug fixes, indicating a maintenance-oriented development. A key differentiator is its approach of spying on the global `it` function to precisely determine test context, offering better reliability than static code parsing methods. It integrates `snap-shot-compare` for intelligent, human-readable diffs and supports a data-driven testing mode, which sets it apart from simpler snapshot solutions by offering more advanced testing patterns within the Mocha ecosystem.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `snap-shot-it` with Mocha, showing basic snapshot creation for synchronous values, strings, asynchronous results, and an example of data-driven testing. It includes instructions for running tests and updating snapshots.

/* package.json */
// {
//   "name": "my-test-project",
//   "version": "1.0.0",
//   "devDependencies": {
//     "mocha": "^10.0.0",
//     "chai": "^4.0.0",
//     "snap-shot-it": "7.x.x"
//   },
//   "scripts": {
//     "test": "mocha --require snap-shot-it spec.js"
//   }
// }

/* spec.js */
const snapshot = require('snap-shot-it');
const { expect } = require('chai');

function add(a, b) {
  return a + b;
}

describe('My Math Functions', () => {
  it('adds two numbers correctly', () => {
    const result = add(5, 7);
    snapshot(result); // First snapshot will create __snapshots__/spec.js with '12'
    expect(result).to.equal(12);
  });

  it('handles strings as snapshots', () => {
    const message = "Hello, snapshot world!";
    snapshot(message); // Second snapshot 'Hello, snapshot world!'
    expect(message).to.be.a('string');
  });

  it('can snapshot asynchronous results', async () => {
    const asyncResult = await Promise.resolve({
      id: 1,
      name: 'Async Data',
      timestamp: new Date('2023-01-01T00:00:00Z')
    });
    snapshot(asyncResult); // Third snapshot with object
    expect(asyncResult.id).to.equal(1);
  });

  // Data-driven testing example
  ['foo', 'bar', 'baz'].forEach((value) => {
    it(`processes value ${value}`, () => {
      snapshot(`processed-${value}`); // Snapshots will be named "processes value foo 1", "processes value bar 1", etc.
    });
  });
});

// To run:
// 1. npm install mocha chai snap-shot-it --save-dev
// 2. Add the 'test' script to package.json
// 3. Run: npm test
// 4. To update snapshots: SNAPSHOT_UPDATE=1 npm test

view raw JSON →