1 | 'use strict'
|
2 |
|
3 | const la = require('lazy-ass')
|
4 | const is = require('check-more-types')
|
5 | const callsites = require('stack-sites')
|
6 |
|
7 |
|
8 | la(is.object(localStorage), 'missing localStorage')
|
9 |
|
10 | function getFilename () {
|
11 | return 'snap-shot.json'
|
12 | }
|
13 |
|
14 | function loadSnapshots () {
|
15 | const filename = getFilename()
|
16 | let snapshots = localStorage.getItem(filename)
|
17 | if (!snapshots) {
|
18 | snapshots = {}
|
19 | } else {
|
20 | snapshots = JSON.parse(snapshots)
|
21 | }
|
22 | return snapshots
|
23 | }
|
24 |
|
25 | function saveSnapshots (snapshots) {
|
26 | const filename = getFilename()
|
27 | const s = JSON.stringify(snapshots, null, 2) + '\n'
|
28 | localStorage.setItem(filename, s)
|
29 | return snapshots
|
30 | }
|
31 |
|
32 | function init () {
|
33 |
|
34 | const sites = callsites()
|
35 | la(sites.length, 'missing callsite')
|
36 | const specFileUrl = sites[1].filename
|
37 | la(is.webUrl(specFileUrl), 'missing spec url', specFileUrl)
|
38 | console.log('loading spec from', specFileUrl)
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | const pIndex = specFileUrl.indexOf('?p=')
|
45 | const dotJsIndex = specFileUrl.indexOf('.js-', pIndex)
|
46 | const specFile = specFileUrl.substr(pIndex + 3, dotJsIndex - pIndex)
|
47 | console.log('specFile is "%s"', specFile)
|
48 |
|
49 |
|
50 | api.fromCurrentFolder = () => specFile
|
51 |
|
52 |
|
53 | const shouldFetch = api.readFileSync === dummyReadFileSync
|
54 | if (shouldFetch) {
|
55 | return fetch(specFileUrl).then(r => r.text())
|
56 | .then(source => {
|
57 |
|
58 | api.readFileSync = () => source
|
59 | })
|
60 | } else {
|
61 | return Promise.resolve()
|
62 | }
|
63 | }
|
64 |
|
65 | function dummyReadFileSync () {
|
66 | throw new Error(`In the browser, please call snapshot.init()
|
67 | before calling tests, like this:
|
68 | const snapshot = require('snap-shot')
|
69 | beforeEach(snapshot.init)
|
70 | `)
|
71 | }
|
72 |
|
73 |
|
74 |
|
75 | const api = {
|
76 | loadSnapshots,
|
77 | saveSnapshots,
|
78 | init,
|
79 | readFileSync: dummyReadFileSync
|
80 | }
|
81 | module.exports = api
|