snap-shot-core
Save / load named snapshots, useful for tests
Last updated 9 months ago by bahmutov .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install snap-shot-core 
SYNC missed versions from official npm registry.

TODO board

snap-shot-core

Save / load named snapshots, useful for tests

NPM

Build status semantic-release js-standard-style renovate-app badge

This is the snapshot loading and saving utility, used by snap-shot-it and schema-shot projects. Can be used to save snapshots from any testing project.

npm install --save-dev snap-shot-core
const snapShot = require('snap-shot-core')
const what // my object
const out = snapShot.core({
  what,
  file: __filename,    // aliases: file, __filename
  specName: 'my test', // or whatever name you want to give,
  store, // optional function to preprocess the value before storing
  compare: compareFn, // optional function that compares values
  raiser: raiseErrorFn, // optional
  ext: '.test', // default value is '.snapshot.js'
  opts: {
    // see below
  }
})

The returned value contains both the saved value and the snapshot name

let out = snapShot.core({
  what: 42,
  exactSpecName: 'my snapshot'
})
console.log(out)
// {value: 42, key 'my snapshot'}
out = snapShot.core({
  what: 42,
  specName: 'my snapshot'
})
console.log(out)
// auto-increments counter if we are using
// just the spec name
// {value: 42, key 'my snapshot 1'}

When throwing an error on different value, the error instance will still have key property with the final snapshot name.

Save folders

All snapshots are saved in a single folder __snapshots__, even if original spec files are nested. See test-nested-specs example folder.

Store function

Sometimes you want to store not the value itself, but something derived, like the object's schema (check out schema-shot). You can pass a function store that transforms the object before saving. For example if we are only interested in the type of value, we can do the following (paired with the right compare function).

const store = x => typeof x
// expected - previously saved "type of" value
// value - current original value
const compare = (
  { expected, value } // return Result
) =>
  snapShot({
    what,
    store,
    compare,
  })

Note: by default multi line text is saves using ES6 template string, while everything else is saved using normal serialization using jsesc.

Compare function

A function to compare expected and actual value should return Result instance, preferably Folktable.Result. A simple one could be

const Result = require('folktale/result')
function compare({ expected, value }) {
  const e = JSON.stringify(expected)
  const v = JSON.stringify(value)
  if (e === v) {
    return Result.Ok()
  }
  return Result.Error(`${e} !== ${v}`)
}

Another one, that compares values by type could be even simpler

const sameTypes = (a, b) => typeof a === typeof b

const compareTypes = ({ expected, value }) =>
  sameTypes(expected, value) ? Result.Ok() : Result.Error('types are different')

Note input is an object {expected, value} and if there is a difference you should describe it as a string Result.Error(<difference string>). Why does it return a Result? Because it makes life easier.

Raise function

Default function will compare current and loaded values using compare function and if the values are different will throw an error. You can provide your own function to fail a test differently. Your function will be called with these parameters

raiser({
  value, // current value
  expected, // loaded value
  specName, // the name of the test
  compare, // compare function
})

Default raiser function just throws an Error with good message.

Returned value

The snapShotCore function returns the expected value. If this is the first time, it will be store(what) value. Otherwise it will be the loaded expected value.

Options

You can pass several options to control the behavior. I usually grab them from the environment variables.

  • show - log snapshot value when saving new one
  • dryRun - only show the new snapshot value, but do not save it
  • update - override snapshot value with the new one if there is difference
  • ci - the tests are running on CI, which should disallow saving snapshots
  • sortSnapshots - enable sorting snapshots by name when saving (default is false)
  • useRelativePath - use relative paths inside __snapshots__ folder to recreate folder structure to mimic spec file relative path. Default is false.
// for example to use environment variables
const opts = {
  show: Boolean(process.env.SHOW),
  dryRun: Boolean(process.env.DRY),
  update: Boolean(process.env.UPDATE),
  ci: Boolean(process.env.CI),
  sortSnapshots: false,
  useRelativePath: false
}
snapShot.core({
  what,
  file: __filename,
  specName: 'my test',
  compare: compareFn,
  ext: '.test',
  opts,
})

If opts.ci is not set, it will use is-ci to determine if running on CI or not.

useRelativePath

When you pass useRelativePath: true option, the folder structure inside the __snapshots__ folder will recreate the folder paths to the spec. For example if the specs are in subfolders:

specs/
  foo/
    spec.js
  bar/
    spec.js

Then output snapshots will be saved as

__snapshots__/
  specs/
    foo/
      spec.js.snapshot.js
    bar/
      spec.js.snapshot.js

Pruning snapshots

When test names change or tests are updated, new snapshots are saved, but old ones remain in the snapshot file. To prune the old snapshots, the test runner can pass all current spec names to prune all other ones. Just call .prune() method and pass the following options

* tests: list of current tests. Each object should have
  file: the full test filename
  specName: the full title of the test
* ext: optional snapshot filename extension

For example see src/prune-spec.js

note this can still leave old snapshot files, if the spec has no tests running or has been renamed.

note 2 if you run tests with .only it will remove all other snapshots in that file. This is normal, you will recreated all snapshots once you run all the tests again.

Exact snapshot name

Sometimes you do not want to auto increment the snapshots, or use default test name. In this case you can pass exactSpecName to just save the snapshot with that key.

snapShot.core({
  what: 42,
  exactSpecName: 'computed value',
  file: __filename,
})

The snapshot file will have

exports['computed value'] = 42

Text snapshots

When saving strings, the snapshot will be surrounded by newlines to avoid extra lone first line (looking like exports["name"] = ...). So when saving snapshot text

line 1
line 2

the snapshot file will have

exports['name'] = `
line 1
line 2
`

The newlines will be trimmed automatically when loading the snapshot value.

Debugging

Run the code with DEBUG=snap-shot-core option to see more log messages. During testing you can see additional output by adding DEBUG=test environment variable (or both DEBUG=snap-shot-core,test).

If you want verbose output, use DEBUG=snap-shot-core*

Testing in watch mode

In case you execute your tests in watch mode and you notice the snapshots are always new-created for the same set of tests, then you need to restore the counters per file.

tape example:

//foo.test.js
const test = require('tape')
const snapShot = require('snap-shot-core')

test.onFinish(snapShot.restore)

test('one test', function(t) {
  t.plan(1)
  snapShot.core({
    what: 1,
    file: __filename,
    specName: 'one test',
  })
})

You can restore / reset a counter for a particular test

const snapShot = require('snap-shot-core')
snapShot.restore({
  file: __filename,
  specName: 'this test',
})

Escaping values

Because the snapshots are saved as template literals, back ticks and other "niceties" have to be escaped. This module uses jsesc module to do string escaping. Currently only the minimal set of characters is escaped.

Resaving snaphots

You can re-save snapshot file (for example to escape it again, or to resort the snapshots by name) using bin/resave-snapshots.js script. After installing this module, run bin script

$(npm bin)/resave-snapshots [--sort] snapshot-filename

To just re-escape the snapshots omit the --sort flag.

Small print

Author: Gleb Bahmutov <gleb.bahmutov@gmail.com> © 2017

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

MIT License

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.

Current Tags

  • 10.2.1                                ...           latest (9 months ago)

62 Versions

  • 10.2.1                                ...           9 months ago
  • 10.2.0                                ...           a year ago
  • 10.1.1                                ...           2 years ago
  • 10.1.0                                ...           2 years ago
  • 10.0.1                                ...           2 years ago
  • 10.0.0                                ...           2 years ago
  • 9.0.0                                ...           2 years ago
  • 8.1.0                                ...           2 years ago
  • 8.0.3                                ...           2 years ago
  • 8.0.2                                ...           2 years ago
  • 8.0.1                                ...           2 years ago
  • 8.0.0                                ...           2 years ago
  • 7.4.0                                ...           2 years ago
  • 7.3.0                                ...           2 years ago
  • 7.2.0                                ...           2 years ago
  • 7.1.15                                ...           2 years ago
  • 7.1.14                                ...           2 years ago
  • 7.1.13                                ...           2 years ago
  • 7.1.12                                ...           2 years ago
  • 7.1.11                                ...           2 years ago
  • 7.1.10                                ...           2 years ago
  • 7.1.9                                ...           2 years ago
  • 7.1.8                                ...           2 years ago
  • 7.1.7                                ...           2 years ago
  • 7.1.6                                ...           2 years ago
  • 7.1.5                                ...           2 years ago
  • 7.1.4                                ...           2 years ago
  • 7.1.3                                ...           2 years ago
  • 7.1.2                                ...           2 years ago
  • 7.1.1                                ...           2 years ago
  • 7.1.0                                ...           2 years ago
  • 7.0.0                                ...           2 years ago
  • 6.0.1                                ...           3 years ago
  • 6.0.0                                ...           3 years ago
  • 5.0.4                                ...           3 years ago
  • 5.0.3                                ...           3 years ago
  • 5.0.2                                ...           3 years ago
  • 5.0.1                                ...           3 years ago
  • 5.0.0                                ...           3 years ago
  • 4.3.0                                ...           3 years ago
  • 4.2.0                                ...           3 years ago
  • 4.1.0                                ...           3 years ago
  • 4.0.0                                ...           3 years ago
  • 3.0.0                                ...           3 years ago
  • 2.0.0                                ...           3 years ago
  • 1.8.0                                ...           3 years ago
  • 1.7.5                                ...           3 years ago
  • 1.7.4                                ...           4 years ago
  • 1.7.3                                ...           4 years ago
  • 1.7.2                                ...           4 years ago
  • 1.7.1                                ...           4 years ago
  • 1.7.0                                ...           4 years ago
  • 1.6.1                                ...           4 years ago
  • 1.6.0                                ...           4 years ago
  • 1.5.0                                ...           4 years ago
  • 1.4.0                                ...           4 years ago
  • 1.3.0                                ...           4 years ago
  • 1.2.2                                ...           4 years ago
  • 1.2.1                                ...           4 years ago
  • 1.2.0                                ...           4 years ago
  • 1.1.0                                ...           4 years ago
  • 1.0.0                                ...           4 years ago
Maintainers (1)
Downloads
Today 0
This Week 7
This Month 89
Last Day 1
Last Week 67
Last Month 46
Dependencies (13)
Dev Dependencies (20)

Copyright 2014 - 2017 © taobao.org |