Mocha Snapshot Testing Utility
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
-
Error: 42 !== 80
cause A previously saved snapshot value does not match the current test output, indicating a regression or an intentional change.fixVerify if the change is intentional. If it is, run your tests with `SNAPSHOT_UPDATE=1 npm test` to update the snapshot file. Otherwise, fix the code causing the unexpected output. -
Cannot read property 'afterAll' of undefined
cause Running versions of `snap-shot-it` older than 7.9.2 with a test suite where all tests are skipped, which could lead to a crash in the `afterAll` hook.fixUpgrade to `snap-shot-it@7.9.2` or newer to resolve the `afterAll` hook crash. Alternatively, ensure at least one test is not skipped. -
SyntaxError: Unexpected token 'export' or 'import'
cause Attempting to use ES Module syntax (`import`) in a CommonJS environment or vice-versa without proper configuration (e.g., `"type": "module"` in `package.json`).fixEnsure your project's module system is correctly configured. For CommonJS, use `const snapshot = require('snap-shot-it')`. For ES Modules, use `import snapshot from 'snap-shot-it'` and verify `package.json` specifies `"type": "module"` or files use `.mjs` extensions.
Warnings
- breaking Starting with version 7.9.1, `snap-shot-it` requires Node.js version 8 or above. Older Node.js versions are no longer supported.
- gotcha When using named snapshots (e.g., `snapshot('my name', value)`), the names must be unique within a single spec file by default. Duplicates will lead to unexpected behavior unless explicitly allowed.
- gotcha To update, dry-run, or view snapshots, you must use specific environment variables (e.g., `SNAPSHOT_UPDATE=1`, `SNAPSHOT_DRY=1`, `SNAPSHOT_SHOW=1`) when running your tests.
- gotcha `snap-shot-it` relies on spying on Mocha's global `it` function to determine test context. This approach, while effective, might cause conflicts or unexpected behavior in highly customized Mocha setups or when combined with other test utilities that also modify global test runner functions.
Install
-
npm install snap-shot-it -
yarn add snap-shot-it -
pnpm add snap-shot-it
Imports
- snapshot
const { snapshot } = require('snap-shot-it')const snapshot = require('snap-shot-it') - snapshot
import { snapshot } from 'snap-shot-it'import snapshot from 'snap-shot-it'
Quickstart
/* 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