UNPKG

2.46 kBJavaScriptView Raw
1'use strict'
2
3const la = require('lazy-ass')
4const is = require('check-more-types')
5
6/* global localStorage, fetch */
7la(is.object(localStorage), 'missing localStorage')
8la(is.fn(fetch), 'missing fetch')
9
10function getFilename () {
11 return 'snap-shot.json'
12}
13
14function 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
25function 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
32function init () {
33 // for now disable
34 return Promise.resolve()
35
36 // find out the source for all test -> this spec file
37 // const sites = callsites()
38 // la(sites.length, 'missing callsite')
39 // const specFileUrl = sites[1].filename
40 // la(is.webUrl(specFileUrl), 'missing spec url', specFileUrl)
41 // console.log('loading spec from', specFileUrl)
42
43 // // specFileUrl is something like
44 // // http://localhost:49829/__cypress/tests?p=cypress/integration/spec.js-438
45 // // we will need to get "true" filename which in this case should be
46 // // cypress/integration/spec.js
47 // const pIndex = specFileUrl.indexOf('?p=')
48 // const dotJsIndex = specFileUrl.indexOf('.js-', pIndex)
49 // const specFile = specFileUrl.substr(pIndex + 3, dotJsIndex - pIndex)
50 // console.log('specFile is "%s"', specFile)
51
52 // // ignore arguments for now
53 // api.fromCurrentFolder = () => specFile
54
55 // // cache the fetched source, otherwise every test fetches it
56 // const shouldFetch = api.readFileSync === dummyReadFileSync
57 // if (shouldFetch) {
58 // return fetch(specFileUrl).then(r => r.text())
59 // .then(source => {
60 // // ignores filename for now
61 // api.readFileSync = () => source
62 // })
63 // } else {
64 // return Promise.resolve()
65 // }
66}
67
68function dummyReadFileSync () {
69 throw new Error(`In the browser, please call snapshot.init()
70 before calling tests, like this:
71 const snapshot = require('snap-shot')
72 beforeEach(snapshot.init)
73 `)
74}
75
76// TODO replace exposed API with error methods that wait id:1
77// Gleb Bahmutov
78// gleb.bahmutov@gmail.com
79// https://github.com/bahmutov/snap-shot-core/issues/86
80// until "init" is called
81const api = {
82 loadSnapshots,
83 saveSnapshots,
84 init,
85 readFileSync: dummyReadFileSync
86}
87module.exports = api