/
snapshot.js
51 lines (45 loc) · 1.41 KB
/
snapshot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'use strict'
const writeFile = require('write-file-atomic')
const fs = require('fs')
const mkdirp = require('mkdirp')
const path = require('path')
class Snapshot {
constructor (test) {
this.indexes = new Map()
this.test = test
this.file = path.resolve(
process.cwd(),
'tap-snapshots',
this.test.fullname.replace(/[^a-zA-Z0-9\._\-]+/g, '-')
)
this.snapshot = null
}
// should only ever call _one_ of match/save
match (data, message) {
// XXX test line-by-line instead of all at once
const index = this.indexes.get(message) || 0
this.indexes.set(message, index + 1)
try {
this.snapshot = this.snapshot || require(this.file)
} catch (er) {
throw new Error('Snapshot file not found\n' +
'Run with TAP_SNAPSHOT=1 in the environment\n' +
'to create snapshot files')
}
return this.snapshot[message + '_' + index] === data
}
snap (data, message) {
const index = this.indexes.get(message) || 0
this.indexes.set(message, index + 1)
this.snapshot = this.snapshot || {}
this.snapshot[message + '_' + index] = data
}
save () {
const data = `'use strict'\n` + (
Object.keys(this.snapshot).map(s =>
`exports[\`${s}\`] = \`${this.snapshot[s]}\`\n`).join('\n'))
mkdirp.sync(path.dirname(this.file))
writeFile.sync(this.file, data, 'utf8')
}
}
module.exports = Snapshot