UNPKG

2.72 kBJavaScriptView Raw
1'use strict'
2
3const la = require('lazy-ass')
4const is = require('check-more-types')
5const callsites = require('stack-sites')
6
7// storage adapter for Cypress E2E testing tool
8
9/* global cy, expect, fetch */
10const filename = 'snap-shot.json'
11
12let snapshots
13
14function loadSnapshots () {
15 return snapshots
16}
17
18function saveSnapshots (snapshots) {
19 const text = JSON.stringify(snapshots, null, 2) + '\n'
20 cy.writeFile(filename, text)
21}
22
23function init () {
24 // find out the source for all test -> this spec file
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 // specFileUrl is something like
32 // http://localhost:49829/__cypress/tests?p=cypress/integration/spec.js-438
33 // we will need to get "true" filename which in this case should be
34 // cypress/integration/spec.js
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 // ignore arguments for now
41 api.fromCurrentFolder = () => specFile
42
43 // cache the fetched source, otherwise every test fetches it
44 const shouldFetch = api.readFileSync === dummyReadFileSync
45 if (shouldFetch) {
46 return fetch(specFileUrl).then(r => r.text())
47 .then(source => {
48 // ignores filename for now
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 // the JSON is wrapped in webpack wrapper ;)
60 const req = eval(text) // eslint-disable-line no-eval
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
73function raiseIfDifferent ({value, expected}) {
74 cy.then(() => {
75 expect(value).to.equal(expected)
76 })
77}
78
79function 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// TODO replace exposed API with error methods that wait
88// until "init" is called
89const api = {
90 loadSnapshots,
91 saveSnapshots,
92 init,
93 readFileSync: dummyReadFileSync,
94 raiseIfDifferent
95}
96module.exports = api