{"id":12047,"library":"snap-shot-it","title":"Mocha Snapshot Testing Utility","description":"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.","status":"maintenance","version":"7.9.10","language":"javascript","source_language":"en","source_url":"https://github.com/bahmutov/snap-shot-it","tags":["javascript","bdd","mocha","snap-shot","snapshot","tdd","test","testing","typescript"],"install":[{"cmd":"npm install snap-shot-it","lang":"bash","label":"npm"},{"cmd":"yarn add snap-shot-it","lang":"bash","label":"yarn"},{"cmd":"pnpm add snap-shot-it","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides the core logic for loading and saving snapshots.","package":"snap-shot-core","optional":false},{"reason":"Used for intelligent, human-readable diffing when snapshots diverge.","package":"snap-shot-compare","optional":false},{"reason":"The intended test runner for this utility, expected to be installed as a dev dependency in the consuming project.","package":"mocha","optional":true}],"imports":[{"note":"The primary export is a default function. Use this pattern for CommonJS modules, typically in Mocha test files.","wrong":"const { snapshot } = require('snap-shot-it')","symbol":"snapshot","correct":"const snapshot = require('snap-shot-it')"},{"note":"For ES Modules and TypeScript, import the default function. The package provides TypeScript definitions for `snapshot` and its options.","wrong":"import { snapshot } from 'snap-shot-it'","symbol":"snapshot","correct":"import snapshot from 'snap-shot-it'"}],"quickstart":{"code":"/* package.json */\n// {\n//   \"name\": \"my-test-project\",\n//   \"version\": \"1.0.0\",\n//   \"devDependencies\": {\n//     \"mocha\": \"^10.0.0\",\n//     \"chai\": \"^4.0.0\",\n//     \"snap-shot-it\": \"7.x.x\"\n//   },\n//   \"scripts\": {\n//     \"test\": \"mocha --require snap-shot-it spec.js\"\n//   }\n// }\n\n/* spec.js */\nconst snapshot = require('snap-shot-it');\nconst { expect } = require('chai');\n\nfunction add(a, b) {\n  return a + b;\n}\n\ndescribe('My Math Functions', () => {\n  it('adds two numbers correctly', () => {\n    const result = add(5, 7);\n    snapshot(result); // First snapshot will create __snapshots__/spec.js with '12'\n    expect(result).to.equal(12);\n  });\n\n  it('handles strings as snapshots', () => {\n    const message = \"Hello, snapshot world!\";\n    snapshot(message); // Second snapshot 'Hello, snapshot world!'\n    expect(message).to.be.a('string');\n  });\n\n  it('can snapshot asynchronous results', async () => {\n    const asyncResult = await Promise.resolve({\n      id: 1,\n      name: 'Async Data',\n      timestamp: new Date('2023-01-01T00:00:00Z')\n    });\n    snapshot(asyncResult); // Third snapshot with object\n    expect(asyncResult.id).to.equal(1);\n  });\n\n  // Data-driven testing example\n  ['foo', 'bar', 'baz'].forEach((value) => {\n    it(`processes value ${value}`, () => {\n      snapshot(`processed-${value}`); // Snapshots will be named \"processes value foo 1\", \"processes value bar 1\", etc.\n    });\n  });\n});\n\n// To run:\n// 1. npm install mocha chai snap-shot-it --save-dev\n// 2. Add the 'test' script to package.json\n// 3. Run: npm test\n// 4. To update snapshots: SNAPSHOT_UPDATE=1 npm test","lang":"javascript","description":"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."},"warnings":[{"fix":"Upgrade your Node.js environment to version 8.x or newer.","message":"Starting with version 7.9.1, `snap-shot-it` requires Node.js version 8 or above. Older Node.js versions are no longer supported.","severity":"breaking","affected_versions":">=7.9.1"},{"fix":"Ensure each named snapshot has a unique name per spec file. If intentional sharing is required, pass `{ allowSharedSnapshot: true }` as an option: `snapshot('my shared snapshot', value, { allowSharedSnapshot: true })`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Prefix your test command with the desired environment variable, e.g., `SNAPSHOT_UPDATE=1 npm test` to update snapshots.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If conflicts arise, review your test runner configuration and other test utilities to identify potential interactions with global `it` modifications. Consider isolating tests or using alternative snapshot solutions if deep customization is unavoidable.","message":"`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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Verify 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.","cause":"A previously saved snapshot value does not match the current test output, indicating a regression or an intentional change.","error":"Error: 42 !== 80"},{"fix":"Upgrade to `snap-shot-it@7.9.2` or newer to resolve the `afterAll` hook crash. Alternatively, ensure at least one test is not skipped.","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.","error":"Cannot read property 'afterAll' of undefined"},{"fix":"Ensure 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.","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`).","error":"SyntaxError: Unexpected token 'export' or 'import'"}],"ecosystem":"npm"}