UNPKG

2.23 kBJavaScriptView Raw
1'use strict'
2
3const la = require('lazy-ass')
4const is = require('check-more-types')
5const callsites = require('stack-sites')
6
7/* global localStorage, fetch */
8la(is.object(localStorage), 'missing localStorage')
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 // find out the source for all test -> this spec file
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 // specFileUrl is something like
41 // http://localhost:49829/__cypress/tests?p=cypress/integration/spec.js-438
42 // we will need to get "true" filename which in this case should be
43 // cypress/integration/spec.js
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 // ignore arguments for now
50 api.fromCurrentFolder = () => specFile
51
52 // cache the fetched source, otherwise every test fetches it
53 const shouldFetch = api.readFileSync === dummyReadFileSync
54 if (shouldFetch) {
55 return fetch(specFileUrl).then(r => r.text())
56 .then(source => {
57 // ignores filename for now
58 api.readFileSync = () => source
59 })
60 } else {
61 return Promise.resolve()
62 }
63}
64
65function 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// TODO replace exposed API with error methods that wait
74// until "init" is called
75const api = {
76 loadSnapshots,
77 saveSnapshots,
78 init,
79 readFileSync: dummyReadFileSync
80}
81module.exports = api