• Stars
    star
    101
  • Rank 338,166 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Chai assertion that provides Jest's snapshot testing

chai-jest-snapshot

Chai assertion for jest-snapshot. See Jest 14.0: React Snapshot Testing for background knowledge about snapshot testing.

Installation

On the command line:

$ npm install --save-dev chai-jest-snapshot

Usage

There are four different ways to use chai-jest-snapshot.

Mocha Configuration Mode (Recommended for Mocha Users)

If you are using mocha as your test runner, it is recommended to use chai-jest-snapshot in "mocha configuration mode".

Note: do not use an arrow function for the beforeEach as these will not receive the correct this value provided by mocha.

In your test setup file:

import chai from "chai";
import chaiJestSnapshot from "chai-jest-snapshot";

chai.use(chaiJestSnapshot);

before(function() {
  chaiJestSnapshot.resetSnapshotRegistry();
});

beforeEach(function() {
  chaiJestSnapshot.configureUsingMochaContext(this);
});

In your spec file(s) (as an example):

import React from "react";
import renderer from "react-test-renderer";
import { expect } from "chai";
import Link from "./Link";

describe("Link", function() {
  it("renders correctly", () => {
    const tree = renderer.create(
      <Link page="http://www.facebook.com">Facebook</Link>
    ).toJSON();
    expect(tree).to.matchSnapshot();
  });
});

This will automatically write snapshots to a file with the same name as your test file, with .snap added to the end. This will also choose snapshot names based on the test name, adding a number to the end based on the number of times matchSnapshot was called in each test (similar to jest).

In this mode, to update a single snapshot, you can pass true as an argument to matchSnapshot:

expect(tree).to.matchSnapshot(true);

If you want to update all snapshots without adding true to each one, set the environment variable CHAI_JEST_SNAPSHOT_UPDATE_ALL to "true":

# assuming `npm test` runs your tests:
# sh/bash/zsh
$ CHAI_JEST_SNAPSHOT_UPDATE_ALL=true npm test
# fish
$ env CHAI_JEST_SNAPSHOT_UPDATE_ALL=true npm test

This behaves similarly to running jest -u.

If you want tests to fail when a snapshot is missing (instead of writing a new one), set the environment variable CI to "true":

# assuming `npm test` runs your tests:
# sh/bash/zsh
$ CI=true npm test
# fish
$ env CI=true npm test

This behaves similarly to running jest --ci.

Jest Configuration Mode (Recommended for Jest Users)

If you are using Jest, but prefer Chai assertions, you don’t have anything to configure except loading the plugin itself: the matchSnapshot Chai assertion will automatically delegate to Jest’s built-in snapshot capability, so all usual options, settings, CLI flags, method arguments, etc. will work out of the box.

import chai from "chai";
import chaiJestSnapshot from "chai-jest-snapshot";

chai.use(chaiJestSnapshot);

Framework-agnostic Configuration Mode (Recommended for Non-Mocha/Jest Users)

If you are using neither mocha nor Jest as your test runner, it is recommended to use chai-jest-snapshot in "framework-agnostic configuration mode".

In your test setup file:

import chai from "chai";
import chaiJestSnapshot from "chai-jest-snapshot";

chai.use(chaiJestSnapshot);

before(function() {
  // In order for watch mode to work correctly, the snapshot registry needs to
  // be reset at the beginning of each suite run. In mocha, `before` callbacks
  // are called before the whole suite runs, but in other test runners you may
  // need to run this somewhere else; for example, in jasmine, you'd put it in a
  // `beforeAll` instead of `before`.
  chaiJestSnapshot.resetSnapshotRegistry();
});

In your spec file(s) (as an example):

import React from "react";
import renderer from "react-test-renderer";
import { expect } from "chai";
import Link from "./Link";

describe("Link", function() {
  beforeEach(function() {
    chaiJestSnapshot.setFilename(__filename + ".snap");
  });

  it("renders correctly", () => {
    // There may be a way to automate this in your test runner; for example,
    // getting the test name in the beforeEach callback, or using a custom
    // reporter to hook into the test lifecycle.
    chaiJestSnapshot.setTestName("Link renders correctly");

    const tree = renderer.create(
      <Link page="http://www.facebook.com">Facebook</Link>
    ).toJSON();
    expect(tree).to.matchSnapshot();
  });
});

This will write snapshots to the file name you specify, (in this example, a file with the same name and location as the spec file, but with .snap added to the end). This will use whatever snapshot name you specify as a template, adding a number to the end based on the number of times matchSnapshot was called using the same file name and snapshot name (similar to what jest does).

In this mode, to update a single snapshot, you can pass true as an argument to matchSnapshot:

expect(tree).to.matchSnapshot(true);

If you want to update all snapshots without adding true to each one, set the environment variable CHAI_JEST_SNAPSHOT_UPDATE_ALL to "true":

# assuming `npm test` runs your tests:
# sh/bash/zsh
$ CHAI_JEST_SNAPSHOT_UPDATE_ALL=true npm test
# fish
$ env CHAI_JEST_SNAPSHOT_UPDATE_ALL=true npm test

This behaves similarly to running jest -u.

If you want tests to fail when a snapshot is missing (instead of writing a new one), set the environment variable CI to "true":

# assuming `npm test` runs your tests:
# sh/bash/zsh
$ CI=true npm test
# fish
$ env CI=true npm test

This behaves similarly to running jest --ci.

Manual Mode

If Mocha Configuration Mode or Framework-agnostic Configuration Mode do not satisfy your needs, you can use "manual mode".

In your test setup file:

import chai from "chai";
import chaiJestSnapshot from "chai-jest-snapshot";

chai.use(chaiJestSnapshot);

In your spec file(s) (as an example):

import React from "react";
import renderer from "react-test-renderer";
import { expect } from "chai";
import Link from "./Link";

describe("Link", function() {
  it("renders correctly", () => {
    const tree = renderer.create(
      <Link page="http://www.facebook.com">Facebook</Link>
    ).toJSON();

    let snapshotFilename = __filename + ".snap";
    let snapshotName = "Link renders correctly";
    expect(tree).to.matchSnapshot(snapshotFilename, snapshotName);
  });
});

This will write snapshots to the file name you specify, (in this example, a file with the same name and location as the spec file, but with .snap added to the end). This will use whatever snapshot name you specify as the snapshot name. NOTE: unlike other modes, this mode does not add a number to the end of the snapshot name.

In this mode, to update a single snapshot, you can pass true as an extra, third argument to matchSnapshot:

expect(tree).to.matchSnapshot(snapshotFilename, snapshotName, true);

If you want to update all snapshots without adding true to each one, set the environment variable CHAI_JEST_SNAPSHOT_UPDATE_ALL to "true":

# assuming `npm test` runs your tests:
# sh/bash/zsh
$ CHAI_JEST_SNAPSHOT_UPDATE_ALL=true npm test
# fish
$ env CHAI_JEST_SNAPSHOT_UPDATE_ALL=true npm test

This behaves similarly to running jest -u.

If you want tests to fail when a snapshot is missing (instead of writing a new one), set the environment variable CI to "true":

# assuming `npm test` runs your tests:
# sh/bash/zsh
$ CI=true npm test
# fish
$ env CI=true npm test

This behaves similarly to running jest --ci.

Misc. API

addSerializer(serializer: SerializerFunction)

import chaiJestSnapshot from "chai-jest-snapshot";
import enzymeToJson from "enzyme-to-json";

chaiJestSnapshot.addSerializer(enzymeToJson({ deep: true }));

Exposes Jest's addSerializer method. Used to add custom serialization, one example is enzyme-to-json.

Tips

  • If you are referencing __filename or __dirname in your snapshot file names, and compile your tests using babel, you will probably want to use babel-plugin-transform-dirname-filename to ensure your snapshots end up in your source directory instead of the directory where your tests were built (ie dist or build).

Contributing

$ npm install
$ npm test

Pull Requests and Issues welcome

More Repositories

1

hex-engine

A modern 2D game engine for the browser.
TypeScript
661
star
2

fs-remote

📡 Drop-in replacement for fs that lets you write to the filesystem from the browser
JavaScript
235
star
3

switch-joy-con

Use Nintendo Switch Joy-Cons as input devices (Bluetooth)
JavaScript
196
star
4

safety-match

Rust-style pattern matching for TypeScript
TypeScript
178
star
5

pheno

Simple, lightweight at-runtime type checking functions, with full TypeScript support
TypeScript
129
star
6

eslint-config-unobtrusive

💛 ESLint config that only helps you, and otherwise stays out of your way
JavaScript
117
star
7

suchibot

A cross-platform AutoHotKey-like thing with TypeScript as its scripting language
TypeScript
99
star
8

react-state-tree

Drop-in replacement for useState that persists your state into a redux-like state tree
TypeScript
98
star
9

yavascript

shell script replacement; write shell scripts in js instead of bash, then run them with a single statically-linked file
TypeScript
76
star
10

react-testing-example-lockscreen

JavaScript
72
star
11

react-send

📨 Separate your component's markup from their position in the render tree
JavaScript
70
star
12

test-it

Test-It is a test framework that gives you the best of node AND the browser.
TypeScript
53
star
13

equivalent-exchange

Transmute one JavaScript string into another by way of mutating its AST. Powered by babel and recast.
TypeScript
52
star
14

transform-imports

Tools that make it easy to codemod imports/requires in your JS
JavaScript
50
star
15

describe-component

📓 Consistent React unit testing with zero boilerplate!
JavaScript
46
star
16

grep-ast

CLI tool to grep files for AST patterns using css-like selector strings
JavaScript
41
star
17

gmod-server-docker

Garry's Mod server running in a docker container, with a volume exposed for customization
Shell
37
star
18

quinci

🤵 Self-hosted, minimal GitHub CI server
JavaScript
34
star
19

webview

A cross-platform program that opens either a URL or files from disk in a native webview.
Go
28
star
20

half-life-vox-console

Website where you can make Half Life's VOX say stuff
JavaScript
27
star
21

eslint-plugin-esquery

Simple, user-created ESLint rules, right in their eslint config
JavaScript
22
star
22

line-sticker-downloader

Tool that downloads stickers or emojis from the LINE store
JavaScript
22
star
23

require-browser

Easy-to-use require function for your browser
JavaScript
21
star
24

use-legacy-state

🦅 Custom React hook; drop-in replacement for this.setState
JavaScript
20
star
25

prs-merged-since

CLI and JS API to list all PRs merged into a GitHub repo since a given tag
JavaScript
19
star
26

run-on-server

👩‍💻 API generator that lets you write code as if you had serverside eval on the client
JavaScript
18
star
27

serializable-types

Runtime type assertion and serialization system
JavaScript
15
star
28

glomp

Lightweight, clearly-defined alternative to file glob strings
TypeScript
15
star
29

popularity-contest

Find the most-imported symbols in your JavaScript project
JavaScript
13
star
30

webview-node

Node wrapper around suchipi/webview.
JavaScript
13
star
31

react-boxxy

📦 An extendable base component for React DOM.
JavaScript
12
star
32

arkit-face-blendshapes

A website which shows examples of the various blendshapes that can be animated using ARKit.
JavaScript
12
star
33

atom-morpher

Atom Package that helps you run code transformations on the current buffer
JavaScript
11
star
34

convert-to-dts

Convert some JavaScript/TypeScript code string into a .d.ts TypeScript Declaration code string
TypeScript
11
star
35

nice-path

treat filesystem paths as objects and distinguish between relative/absolute paths
TypeScript
10
star
36

simple-codemod-script

How to write your own JS/TS codemods, with comments and resources
TypeScript
10
star
37

parallel-park

Parallel/concurrent async work, optionally using multiple threads or processes
TypeScript
10
star
38

cleffa

CLI utility that parses argv, loads your specified file, and passes the parsed argv into your file's exported function. Supports ESM/TypeScript/etc out of the box.
JavaScript
10
star
39

mark-applier

Markdown-to-Website Generator, GitHub README style
TypeScript
10
star
40

has-shape

Very tiny function that checks if an object/array/value is shaped like another, with TypeScript type refining.
JavaScript
9
star
41

match-discriminated-union

TypeScript pattern match function for any discriminated union type
TypeScript
8
star
42

iterate-all

Converts an iterable, iterable of Promises, or async iterable into a Promise of an Array.
TypeScript
8
star
43

resolve-everything

walk your project's import/require tree and print all the relationships
TypeScript
8
star
44

Polycode-Binaries

Precompiled binaries of the Polycode Lua IDE
7
star
45

concubine

Create your own hooks system like React's
TypeScript
7
star
46

jsxdom

JSX factory that creates HTML elements directly
TypeScript
7
star
47

little-api

A simple JSON-over-HTTP/WebSocket RPC server and client
JavaScript
7
star
48

markdown-slice

tool that prints a subset of a markdown document
TypeScript
7
star
49

xode

Create a customized node binary with additional features
JavaScript
7
star
50

jsh

Tool for writing shell scripts using js.
JavaScript
7
star
51

clip-studio-paint-joycon

Use a Nintendo Switch Joy-Con (L) for Clip Studio Paint hotkeys
JavaScript
7
star
52

pretty-print-error

Formats errors as nice strings with colors
TypeScript
6
star
53

tf2-server-docker

TF2 Server running in a docker container
Dockerfile
6
star
54

kame

A JavaScript bundler/runtime
JavaScript
6
star
55

suchipi-game-controller

Wrapper around the Web Gamepad API
JavaScript
6
star
56

sheep-herder

A game where you're a dog who herds sheep
TypeScript
6
star
57

pokemon-red-intro-recreation

I recreated the Pokemon Red Intro in the browser
TypeScript
6
star
58

yosh

yavascript-based terminal shell
TypeScript
6
star
59

hex-engine-example-hexagon-grid

Example of rendering and interacting with a hexagonal grid in hex engine.
TypeScript
6
star
60

spotify-player

Node API to drive a Spotify browser window
JavaScript
6
star
61

webview-packager

Bundles your web app into a light, native desktop webview application.
JavaScript
6
star
62

lurantis

on-demand module bundler thingy
TypeScript
6
star
63

typescript-assert-utils

Utility types for making assertions about TypeScript types
TypeScript
6
star
64

pretty-print-ast

Formats ASTs as nice readable strings, with colors
TypeScript
5
star
65

commonjs-standalone

Standalone CommonJS loader for any JS engine
JavaScript
5
star
66

hex-engine-tic-tac-toe-example

An example tic-tac-toe game written in Hex Engine.
TypeScript
5
star
67

aseprite-loader

Webpack loader for *.ase/*.aseprite files
JavaScript
5
star
68

js-is

Functions for testing the types of JavaScript values, cross-realm. Has testers for all standard built-in objects/values.
TypeScript
5
star
69

get-nested-bounding-client-rect

Get the bounding client rect of an element relative to the root document, going through iframes
JavaScript
5
star
70

peep-the-horror

A toy you can use to make an impromptu soundboard out of a video (YouTube, etc).
TypeScript
4
star
71

reverse-proxy-cli

barebones reverse-proxy CLI for forwarding requests from one place to another
JavaScript
4
star
72

node-apng2gif

Convert APNG images to GIF
JavaScript
4
star
73

code-preview-from-error

Preview the code an Error came from
JavaScript
4
star
74

clefairy

Typed CLI argv parser and main function wrapper
TypeScript
4
star
75

at-js

Unix command-line utilities for working with data
JavaScript
4
star
76

girlboss-advance

(wip) remote multiplayer gba emulator web interface
Dockerfile
4
star
77

ac-toolkit

Elements that assist in creating animal-crossing-like UI experiences
HTML
4
star
78

midi-to-thirty-dollar-haircut

(bad) script that converts midi files into *.🗿 files for https://gdcolon.com/%F0%9F%97%BF
TypeScript
4
star
79

tts-repl

simple interactive text-to-speech CLI program (shells out to AWS CLI for Amazon Polly and plays with ffplay)
TypeScript
4
star
80

js-sandbox-demo

Using QuickJS to implement a sandbox wherein it's safe to execute untrusted JavaScript code.
TypeScript
4
star
81

join

tiny CLI tool: JSON array to stdin -> join with delimiter -> string to stdout
Shell
4
star
82

visualize-ansi-codes

Replace ansi escape sequences with tokens indicating what they are.
TypeScript
3
star
83

extname

command-line utility for finding the extension of a filename/filepath
C
3
star
84

docker-bgb

BGB (GB/GBC Emulator) in docker via web vnc client (no sound)
Dockerfile
3
star
85

jest-node-nw-example

Jest in NW.js
JavaScript
3
star
86

defer

Inside-out promise; lets you call resolve and reject from outside the Promise constructor function.
TypeScript
3
star
87

shinobi

generate ninja build files from js scripts
TypeScript
3
star
88

babel-compare

Compare compilation output between babel 6 and babel 7
TypeScript
3
star
89

modal-synthesis

Package for synthesizing modal sounds using the Web Audio API
TypeScript
3
star
90

workspace-builder

CLI tool that run builds for every yarn workspace in your monorepo
JavaScript
3
star
91

first-base

Integration testing for CLI applications
JavaScript
3
star
92

discord-spotify-bot

Discord bot that plays Spotify in the voice channel
JavaScript
3
star
93

pipe-wrench

Generic, cross-platform IPC streams. Uses named pipes on windows and unix sockets elsewhere
JavaScript
3
star
94

bibarel

walk over a tree, transforming each value
TypeScript
3
star
95

a-mimir

Barebones sleep functions. As simple and boring as it gets
JavaScript
3
star
96

qjsbundle

TypeScript
3
star
97

link-fixer-discord-bot

Discord Bot: when someone posts a message with a twitter.com or x.com link, it replies with a vxtwitter.com version of that link
TypeScript
3
star
98

multi

Redux + Quake-style Netcode = ???
TypeScript
2
star
99

domdom-go

Cross-platform CLI interface to DomDomSoft Anime Downloader
Go
2
star
100

suchipis-color-theme

VSCode color theme
2
star