{"id":21654660,"url":"https://github.com/localvoid/karma-snapshot","last_synced_at":"2025-04-11T21:14:07.250Z","repository":{"id":57155941,"uuid":"97470943","full_name":"localvoid/karma-snapshot","owner":"localvoid","description":":a::vs::b: Karma plugin for snapshot testing","archived":false,"fork":false,"pushed_at":"2018-04-05T08:47:52.000Z","size":84,"stargazers_count":31,"open_issues_count":3,"forks_count":4,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-11T21:14:01.815Z","etag":null,"topics":["karma","snapshot"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/localvoid.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-07-17T11:54:34.000Z","updated_at":"2024-02-07T00:35:56.000Z","dependencies_parsed_at":"2022-08-30T05:32:10.911Z","dependency_job_id":null,"html_url":"https://github.com/localvoid/karma-snapshot","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/localvoid%2Fkarma-snapshot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/localvoid%2Fkarma-snapshot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/localvoid%2Fkarma-snapshot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/localvoid%2Fkarma-snapshot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/localvoid","download_url":"https://codeload.github.com/localvoid/karma-snapshot/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248480427,"owners_count":21110937,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["karma","snapshot"],"created_at":"2024-11-25T08:28:38.172Z","updated_at":"2025-04-11T21:14:07.223Z","avatar_url":"https://github.com/localvoid.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Karma Plugin for Snapshot Testing\n\n`karma-snapshot` provides a communication layer between browser and [Karma](http://karma-runner.github.io/) to store and\nretrieve snapshots.\n\n![karma-snapshot Example][example]\n\n## Supported Assertion Libraries\n\n- [chai](https://github.com/localvoid/chai-karma-snapshot)\n- [iko](https://github.com/localvoid/iko)\n\n## Snapshot Format\n\nSnapshot can be stored in different formats. Right now there are two formats supported: `md` and `indented-md`.\n\n### Markdown Format\n\nThis format is preferred when you specify language for code blocks in an assertion plugin. With this format, code\neditors will automatically highlight syntax of code blocks.\n\n````md\n# `src/html.js`\n\n## `Sub Suite`\n\n####   `HTML Snapshot`\n\n```html\n\u003cdiv\u003e\n  \u003cspan /\u003e\n\u003c/div\u003e\n```\n````\n\n### Indented Markdown Format\n\n```md\n# `src/html.js`\n\n## `Sub Suite`\n\n####   `HTML Snapshot`\n\n    \u003cdiv\u003e\n      \u003cspan /\u003e\n    \u003c/div\u003e\n```\n\n## Snapshot File Path\n\nSnapshot file path is extracted from the name of the root suit cases and stored alongside with a tested files in a\n`__snapshots__` directory.\n\nSnapshot file path can be changed by providing a custom `pathResolver` in snapshot config.\n\n## Usage Example with Mocha and Chai\n\n```sh\n$ npm install karma karma-webpack karma-sourcemap-loader karma-snapshot karma-mocha \\\n              karma-mocha-snapshot karma-mocha-reporter karma-chrome-launcher mocha \\\n              chai chai-karma-snapshot webpack --save-dev\n```\n\nKarma configuration: \n\n```js\n// karma.conf.js\nconst webpack = require(\"webpack\");\n\nmodule.exports = function (config) {\n  config.set({\n    browsers: [\"ChromeHeadless\"],\n    frameworks: [\"mocha\", \"snapshot\", \"mocha-snapshot\"],\n    reporters: [\"mocha\"],\n    preprocessors: {\n      \"**/__snapshots__/**/*.md\": [\"snapshot\"],\n      \"__tests__/index.js\": [\"webpack\", \"sourcemap\"]\n    },\n    files: [\n      \"**/__snapshots__/**/*.md\",\n      \"__tests__/index.js\"\n    ],\n\n    colors: true,\n    autoWatch: true,\n\n    webpack: {\n      devtool: \"inline-source-map\",\n      performance: {\n        hints: false\n      },\n    },\n\n    webpackMiddleware: {\n      stats: \"errors-only\",\n      noInfo: true\n    },\n\n    snapshot: {\n      update: !!process.env.UPDATE,\n      prune: !!process.env.PRUNE,\n    },\n\n    mochaReporter: {\n      showDiff: true,\n    },\n\n    client: {\n      mocha: {\n        reporter: \"html\",\n        ui: \"bdd\",\n      }\n    },\n  });\n};\n```\n\nSource file:\n\n```js\n// src/index.js\n\nexport function test() {\n  return \"Snapshot Test\";\n}\n```\n\nTest file:\n\n```js\n// __tests__/index.js\nimport { use, expect, assert } from \"chai\";\nimport { matchSnapshot } from \"chai-karma-snapshot\";\nimport { test } from \"../src/index.js\";\nuse(matchSnapshot);\n\ndescribe(\"src/index.js\", () =\u003e {\n  it(\"check snapshot\", () =\u003e {\n    // 'expect' syntax\n    expect(test()).to.matchSnapshot();\n    // 'assert' syntax\n    assert.matchSnapshot(test());\n  });\n});\n```\n\nRun tests:\n\n```sh\n$ karma start\n```\n\nUpdate snapshots:\n\n```sh\n$ UPDATE=1 karma start --single-run\n```\n\nPrune snapshots:\n\n```sh\n$ PRUNE=1 karma start --single-run\n```\n\n## Config\n\n```js\nfunction resolve(basePath, suiteName) {\n  return path.join(basePath, \"__snapshots__\", suiteName + \".md\");\n}\n\nconfig.set({\n  ...\n  snapshot: {\n    update: true,           // Run snapshot tests in UPDATE mode (default: false)\n    prune: false,           // Prune unused snapshots (default: false)\n    format: \"indented-md\",  // Snapshot format (default: md)\n    checkSourceFile: true,  // Checks existince of the source file associated with tests (default: false)\n    pathResolver: resolve,  // Custom path resolver,\n    limitUnusedSnapshotsInWarning: -1  // Limit number of unused snapshots reported in the warning\n                                       // -1 means no limit\n\n  }\n});\n```\n\n## Custom Snapshot Format\n\nSnapshot config option `format` also works with custom serialization formats. Custom snapshot serializer should have\ninterface:\n\n```ts\ninterface SnapshotSerializer {\n  serialize: (name: string, suite: SnapshotSuite) =\u003e string,\n  deserialize: (content: string) =\u003e { name: string, suite: SnapshotSuite },\n}\n```\n\n## Internals\n\n### Snapshot Data\n\n`karma-snapshot` plugin is communicating with a browser by assigning a global variable `__snapshot__` on a `window`\nobject.\n\nSnapshot data has a simple data structure:\n\n```ts\ndeclare global {\n  interface Window {\n    __snapshot__: SnapshotState;\n  }\n}\n\ninterface SnapshotState {\n  update?: boolean;\n  suite: SnapshotSuite;\n}\n\ninterface SnapshotSuite {\n  children: { [key: string]: SnapshotSuite };\n  snapshots: { [key: string]: Snapshot[] };\n  visited?: boolean;\n  dirty?: boolean;\n}\n\ninterface Snapshot {\n  lang?: string;\n  code: string;\n  visited?: boolean;\n  dirty?: boolean;\n}\n```\n\nWhen `SnapshotState.update` variable is `true`, it indicates that assertion plugin should run in update mode, and\ninstead of checking snapshots, it should update all values.\n\n`SnapshotState.suite` is a reference to the root suite.\n\n`SnapshotSuite` is a tree with snapshots that has a similar structure to test suites. `children` property is used to\nstore references to children suites, and `snapshots` is used to store snapshot lists for tests in the current snapshot.\nSnapshots are stored as a list because each test can have multiple snapshot checks, and they should be automatically\nindexed by their position.\n\n`Snapshot` is an object that stores details about snapshot. `lang` property indicates which language should be used\nin a markdown format to improve readability. `code` property stores snapshot value that will be checked by an assertion\nplugin.\n\n`visited` is a flag that should be marked by an assertion plugin when it visits suites and snapshots. Visited flags are\nused to  automatically prune removed snapshots.\n\n`dirty` is a flag that should be marked by an assertion plugin when it updates or adds a new snapshot.\n\n### Interface for Assertion Libraries\n\nTo make it easier to add support for assertion libraries, `SnapshotState` has two methods that should be used when\ncreating an API for an assertion library.\n\n```ts\ninterface SnapshotSuite {\n  get(path: string[], index: number): Snapshot | undefined;\n  set(path: string[], index: number, code: string, lang?: string): void;\n  match(received: string, expected: string): boolean;\n}\n```\n\n`get()` method tries to find a `Snapshot` in a current snapshot state. It also automatically marks all nodes on the\n`path` as visited.\n\n`set()` method adds or updates an existing `Snapshot`.\n\n`match()` method checks if two snapshots are matching in normalized form.\n\nHere is an example how it should be used:\n\n```ts\nfunction matchSnapshot(path: string[], index: number, received: string) {\n  if (snapshotState.update) {\n    snapshotState.set(path, index, received);\n  } else {\n    const snapshot = snapshotState.get(path, index);\n    if (!snapshot) {\n      snapshotState.set(path, index, received);\n    } else {\n      const pass = snapshotState.match(received, snapshot.code);\n      if (!pass) {\n        throw new AssertionError(`Received value does not match stored snapshot ${index}`);\n      }\n    }\n  }\n}\n```\n\n[example]: https://localvoid.github.io/karma-snapshot/images/example.png \"karma-snapshot Example\"\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flocalvoid%2Fkarma-snapshot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flocalvoid%2Fkarma-snapshot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flocalvoid%2Fkarma-snapshot/lists"}