UNPKG

2.6 kBJavaScriptView Raw
1'use strict'
2
3const la = require('lazy-ass')
4const is = require('check-more-types')
5const R = require('ramda')
6const debug = require('debug')('snap-shot-store')
7const utils = require('./utils')
8
9function initStore (snapshots = {}) {
10 la(is.object(snapshots), 'expected plain store object', snapshots)
11 let currentSnapshots = R.clone(snapshots)
12
13 return function snapShotCore (
14 {
15 what,
16 value,
17 name,
18 names,
19 store = R.identity,
20 compare = utils.compare,
21 raiser,
22 comment,
23 opts = {}
24 } = {}
25 ) {
26 if (is.empty(arguments) || is.empty(arguments[0])) {
27 return currentSnapshots
28 }
29
30 // a few aliases
31 what = what || value
32 name = name || names
33
34 la(utils.isName(name), 'missing or invalid name', name)
35 la(is.fn(compare), 'missing compare function', compare)
36 la(is.fn(store), 'invalid store function', store)
37 if (!raiser) {
38 raiser = utils.raiseIfDifferent
39 }
40 la(is.fn(raiser), 'invalid raiser function', raiser)
41 la(is.maybe.unemptyString(comment), 'wrong comment type', comment)
42
43 if ('ci' in opts) {
44 debug('is CI environment? %s', Boolean(opts.ci))
45 }
46
47 const setOrCheckValue = any => {
48 const value = utils.strip(any)
49 const expected = utils.findValue({
50 snapshots: currentSnapshots,
51 name,
52 opts
53 })
54 if (expected === undefined) {
55 if (opts.ci) {
56 console.log('current directory', process.cwd())
57 console.log('new value to save: %j', value)
58 // TODO return a lens instead!
59 const key = utils.fullName(name)
60 throw new Error(
61 'Cannot store new snapshot value\n' +
62 'for spec called "' +
63 name +
64 '"\n' +
65 'test key "' +
66 key +
67 '"\n' +
68 'when running on CI (opts.ci = 1)\n' +
69 'see https://github.com/bahmutov/snap-shot-core/issues/5'
70 )
71 }
72
73 const storedValue = store(value)
74 currentSnapshots = utils.storeValue({
75 snapshots: currentSnapshots,
76 name,
77 value: storedValue,
78 comment,
79 opts
80 })
81 return storedValue
82 }
83
84 debug('found snapshot for "%s", value', name, expected)
85 raiser({
86 value,
87 expected,
88 specName: name,
89 compare
90 })
91 return expected
92 }
93
94 if (is.promise(what)) {
95 return what.then(setOrCheckValue)
96 } else {
97 return setOrCheckValue(what)
98 }
99 }
100}
101
102module.exports = {
103 initStore: initStore
104}