Jest-like snapshot feature for the rest of us + data-driven testing
npm install snap-shot
> Jest-like snapshot feature for the rest of us + data-driven testing!
[![NPM][npm-icon] ][npm-url]
[![Build status][ci-image] ][ci-url]
[![semantic-release][semantic-image] ][semantic-url]
[![js-standard-style][standard-image]][standard-url]
[![status][link1]][url1] snap-shot-jest-test - for testing snap-shot against Jest runner (React + JSX)
[![status][link2]][url2] snap-shot-modules-test - for testing against transpiled ES6 modules
[![status][link3]][url3] snap-shot-vue-test - for testing snap-shot inside Jest + Vue.js project
[![status][link4]][url4] snap-shot-jsdom-test - for testing snap-shot using mock DOM adapter and element serialization
[![status][link5]][url5] snap-shot-ava-test - for testing how snap-shot works with [Ava][ava] test framework
[link1]: https://travis-ci.org/bahmutov/snap-shot-jest-test.svg?branch=master
[url1]: https://travis-ci.org/bahmutov/snap-shot-jest-test
[link2]: https://travis-ci.org/bahmutov/snap-shot-modules-test.svg?branch=master
[url2]: https://travis-ci.org/bahmutov/snap-shot-modules-test
[link3]: https://travis-ci.org/bahmutov/snap-shot-vue-test.svg?branch=master
[url3]: https://travis-ci.org/bahmutov/snap-shot-vue-test
[link4]: https://travis-ci.org/bahmutov/snap-shot-jsdom-test.svg?branch=master
[url4]: https://travis-ci.org/bahmutov/snap-shot-jsdom-test
[link5]: https://travis-ci.org/bahmutov/snap-shot-ava-test.svg?branch=master
[url5]: https://travis-ci.org/bahmutov/snap-shot-ava-test
[ava]: https://github.com/avajs/ava
Read Snapshot testing the hard way
I like Jest snapshot
idea and want it without the rest of Jest testing framework. This module is
JUST a single assertion method to be used in BDD frameworks (Mocha, Jasmine)
Also, I really really really wanted to keep API as simple and as "smart"
as possible. Thus snap-shot tries to find the surrounding unit test name
by inspecting its call site
(using stack-sites or
callsites)
and parsing AST of the spec file
(using falafel).
Snapshot values are compared using
variable-diff (objects)
and disparity
(multi line strings). See images/README.md for screenshots.
This function also includes [data-driven][data-driven] testing mode,
similar to [sazerac][sazerac], see Data-driven testing
section below.
[data-driven]: https://hackernoon.com/sazerac-data-driven-testing-for-javascript-e3408ac29d8c#.9s4ikt67d
[sazerac]: https://github.com/mikec/sazerac
Install: npm install --save-dev snap-shot
``js`
const snapshot = require('snap-shot')
// in ES6 code use
import snapshot from 'snap-shot'
it('is 42', () => {
snapshot(42)
})
Run it first time with mocha spec.js.__snapshots__/spec.js.snap-shot
This will create snapshots JSON values file inside.
In general this file should close to Jest format, but the file extension is
different to avoid clashing with Jest persistence logic.
`shis 42 1
$ mocha spec.js
$ cat __snapshots__/spec.js.snap-shot
module.exports[] = 42`
Now modify the spec.js file
`js`
const snapshot = require('snap-shot')
it('is 42', () => {
snapshot(80)
})
`sh`
$ mocha spec.js
1) is 42:
Error: expected 42 got 80
Note snap-shot does not store or handle undefined values, since they
are likely an edge case. If you disagree, open
an issue please.
Note All values are saved as JSON, thus non-serializable values, like
functions are stripped before comparison.
For asynchronous code, please have a function inside the spec before
calling snap-shot or let snap-shot wrap the promise.
`js
it('promise to function', () => {
return Promise.resolve(20)
.then(data => snapshot(data))
})
it('snap-shot can wrap promise', () => {
return snapshot(Promise.resolve('value'))
})
// does NOT work
it('promise to snapshot', () => {
return Promise.resolve(20)
.then(snapshot)
})
`
In the last test, the stack trace from snap-shot cannot get any parent
information, thus it cannot find the unit test.
You can use this assertion inside Jest tests too.
`js`
const snapshot = require('snap-shot')
test('my test', () => {
snapshot(myValue)
})
Should work (including async / await syntax), see
snap-shot-ava-test
for the current status.
`js`
import test from 'ava'
import snapshot from 'snap-shot'
test('concat strings', t => {
snapshot('f' + 'oo')
})
You can easily mock DOM and use snapshots (either in text or JSON format),
see snap-shot-jsdom-test
project.
[jsdom-global]: https://github.com/rstacruz/jsdom-global
If snap-shot finds .babelrc inside the current working folder, it will
try transpiling loaded files using
babel-core API. This makes it useful
for testing React code. For full example see
Link.test.js
If you just want to see what a new schema would be, without saving it,
run the tests with DRY=1 npm test option.
If you want to see the schema and save it, run the tests with SHOW=1 npm test
``
$ SHOW=1 npm test
saving snapshot "spec name" for file ./src/valid-message-spec.js
{ firstLine: 'break(log): new log format',
type: 'major',
scope: 'log',
subject: 'new log format'
}
To update all saved values, run with UPDATE=1 environment variable.
`sh`
$ UPDATE=1 mocha spec.js
To update snapshot inside a single test function, use second argument
`js`
const snapshot = require('snap-shot')
it('is 42', () => {
snapshot(80, true)
})
// snapshot file now has {"is 42": 80)
You can also update a single or several tests when running Mocha by filtering
the tests using grep feature.
`sh`
$ UPDATE=1 mocha -g "test name pattern" *-spec.js
Note most CIs (like Travis, Circle, GitLabCI) define environment variable CI, whichprocess.env.CI
we take into consideration as well. It makes no sense to allow saving snapshot on CI, thus if
the is set, the snapshot MUST exist on disk.
There is no magic in formatting snapshots. Just use any function or compose
with snapshot before comparing. Both choices work
`js
const snapshot = require('snap-shot')
it('compares just keys', () => {
const o = {
foo: Math.random(),
bar: Math.random()
}
snapshot(Object.keys(o))
})
// snapshot will be something like
/*
exports['compares just keys 1'] = [
"foo",
"bar"
]
*/
const compose = (f, g) => x => f(g(x))
const upperCase = x => x.toUpperCase()
const upValue = compose(snapshot, upperCase)
it('compares upper case string', () => {
upValue('foo')
})
/*
exports['compares upper case string 1'] = "FOO"
*/
`
Simple is better. Format the data and then call snapshot.
`js`
it('works', () => {
const domNode = ...
const structure = formatHtml(domNode)
snapshot(structure)
})
Sometimes tests are generated dynamically without hardcoded names. In this
case SHA256 of the test callback function is used to find its value.
`js`
// this still works
const testName = 'variable test name (value 30)'
const value = 30
it(testName, () => {
// this is a test without hard coded name
snapshot(value)
})
// snapshot file will have something like
// exports['465fb... 1'] = 30
The best strategy in this case is to use meaningful name for the callback
function
`js`
const testName = 'variable test name (value 30)'
const value = 30
it(testName, function is30() {
snapshot(value)
})
// snapshot file will have something like
// exports['is30 1'] = 30
A single test can have multiple snapshots.
`jssnap ${k}
it('handles multiple snapshots', () => {
snapshot(1)
snapshot(2)
})
it('uses counter of snapshot calls', () => {
for (let k = 0; k < 10; k += 1) {
snapshot()`
}
})
Writing multiple input / output pairs for a function under test quickly
becomes tedious. Luckily, you can test a function by providing multiple
inputs and a single snapshot of function's behavior will be saved.
`js`
// checks if n is prime
const isPrime = n => ...
it('tests prime', () => {
snapshot(isPrime, 1, 2, 3, 4, 5, 6, 7, 8, 9)
})
The saved snapshot file will have clear mapping between given input and
produced result
`js`
// snapshot file
exports['tests prime 1'] = {
"name": "isPrime",
"behavior": [
{
"given": 1,
"expect": false
},
{
"given": 2,
"expect": true
},
{
"given": 3,
"expect": true
},
{
"given": 4,
"expect": false
},
{
"given": 5,
"expect": true
},
...
]
}
You can also test functions that expect multiple arguments by providing
arrays of inputs.
`js`
const add = (a, b) => a + b
it('checks behavior of binary function add', () => {
snapshot(add, [1, 2], [2, 2], [-5, 5], [10, 11])
})
Again, the snapshot file gives clear picture of the add behavior
`js`
// snapshot file
exports['checks behavior of binary function add 1'] = {
"name": "add",
"behavior": [
{
"given": [
1,
2
],
"expect": 3
},
{
"given": [
2,
2
],
"expect": 4
},
{
"given": [
-5,
5
],
"expect": 0
},
{
"given": [
10,
11
],
"expect": 21
}
]
}
See src/data-driven-spec.js for more examples.
Run with DEBUG=snap-shot environment variable
`sh`
$ DEBUG=snap-shot mocha spec.js
If you want to see messages only when new values are stored use
```
$ DEBUG=save mocha spec.js
save Saved for "is 42 1" snapshot 42
There are special projects that are setup to test this code in isolation
as dependent projects, see above.
* chai-jest-snapshot if
you are using Chai
* schema-shot - it is like snapshot
testing but for dynamic data
(explanation)
Author: Gleb Bahmutov <gleb.bahmutov@gmail.com> © 2017
* @bahmutov
* glebbahmutov.com
* blog
License: MIT - do anything with the code, but don't blame me if it does not work.
Support: if you find any problems with this module, email / tweet /
open issue on Github
Copyright (c) 2017 Gleb Bahmutov <gleb.bahmutov@gmail.com>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
[npm-icon]: https://nodei.co/npm/snap-shot.svg?downloads=true
[npm-url]: https://npmjs.org/package/snap-shot
[ci-image]: https://travis-ci.org/bahmutov/snap-shot.svg?branch=master
[ci-url]: https://travis-ci.org/bahmutov/snap-shot
[semantic-image]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg
[semantic-url]: https://github.com/semantic-release/semantic-release
[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
[standard-url]: http://standardjs.com/