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 |
|
9 |
|
10 | const filename = 'snap-shot.json'
|
11 |
|
12 | let snapshots
|
13 |
|
14 | function loadSnapshots () {
|
15 | return snapshots
|
16 | }
|
17 |
|
18 | function saveSnapshots (snapshots) {
|
19 | const text = JSON.stringify(snapshots, null, 2) + '\n'
|
20 | cy.writeFile(filename, text)
|
21 | }
|
22 |
|
23 | function init () {
|
24 |
|
25 | const sites = callsites()
|
26 | la(sites.length, 'missing callsite')
|
27 | const specFileUrl = sites[1].filename
|
28 | la(is.webUrl(specFileUrl), 'missing spec url', specFileUrl)
|
29 | console.log('loading spec from', specFileUrl)
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | const pIndex = specFileUrl.indexOf('?p=')
|
36 | const dotJsIndex = specFileUrl.indexOf('.js-', pIndex)
|
37 | const specFile = specFileUrl.substr(pIndex + 3, dotJsIndex - pIndex)
|
38 | console.log('specFile is "%s"', specFile)
|
39 |
|
40 |
|
41 | api.fromCurrentFolder = () => specFile
|
42 |
|
43 |
|
44 | const shouldFetch = api.readFileSync === dummyReadFileSync
|
45 | if (shouldFetch) {
|
46 | return fetch(specFileUrl).then(r => r.text())
|
47 | .then(source => {
|
48 |
|
49 | api.readFileSync = () => source
|
50 | })
|
51 | .then(() => {
|
52 | return fetch('/__cypress/tests?p=./' + filename)
|
53 | .then(r => r.text())
|
54 | .then(function loadedText (text) {
|
55 | if (text.includes('BUNDLE_ERROR')) {
|
56 | return Promise.reject(new Error('not found'))
|
57 | }
|
58 | cy.log('loaded snapshots', filename)
|
59 |
|
60 | const req = eval(text)
|
61 | snapshots = req('1')
|
62 | })
|
63 | .catch(err => {
|
64 | console.error(err)
|
65 | snapshots = {}
|
66 | })
|
67 | })
|
68 | } else {
|
69 | return Promise.resolve()
|
70 | }
|
71 | }
|
72 |
|
73 | function raiseIfDifferent ({value, expected}) {
|
74 | cy.then(() => {
|
75 | expect(value).to.equal(expected)
|
76 | })
|
77 | }
|
78 |
|
79 | function dummyReadFileSync () {
|
80 | throw new Error(`In the browser, please call snapshot.init()
|
81 | before calling tests, like this:
|
82 | const snapshot = require('snap-shot')
|
83 | beforeEach(snapshot.init)
|
84 | `)
|
85 | }
|
86 |
|
87 |
|
88 |
|
89 | const api = {
|
90 | loadSnapshots,
|
91 | saveSnapshots,
|
92 | init,
|
93 | readFileSync: dummyReadFileSync,
|
94 | raiseIfDifferent
|
95 | }
|
96 | module.exports = api
|