UNPKG

2.29 kBJavaScriptView Raw
1'use strict'
2
3const la = require('lazy-ass')
4const is = require('check-more-types')
5const disparity = require('disparity')
6const Result = require('folktale/result')
7
8function removeExplanation (text) {
9 return text
10 .split('\n')
11 .filter(x => !x.includes('--- removed'))
12 .filter(x => !x.includes('+++ added'))
13 .filter(x => !x.includes('@@ '))
14 .filter(x => !x.includes('No newline at end of file'))
15 .join('\n')
16 .replace(/\n+$/, '\n')
17}
18
19function textDifference (expected, value, noColor) {
20 const diff = noColor ? disparity.unifiedNoColor : disparity.unified
21 const textDiff = diff(expected, value)
22 return removeExplanation(textDiff)
23}
24
25function compareText (expected, value, noColor, json) {
26 const textDiff = textDifference(expected, value, noColor)
27 if (!textDiff) {
28 return Result.Ok()
29 }
30 if (json) {
31 return Result.Error({
32 message: textDiff,
33 expected,
34 value
35 })
36 }
37 return Result.Error(textDiff)
38}
39
40function repeat (c, n) {
41 let s = ''
42 for (let k = 0; k < n; k += 1) {
43 s += c
44 }
45 return s
46}
47
48function header (text) {
49 la(is.unemptyString(text), 'missing header text', text)
50 const n = text.length
51 const hr = repeat('-', n)
52 return hr + '\n' + text + '\n' + hr + '\n'
53}
54
55function maybeEndNewLine (text) {
56 if (text.endsWith('\n')) {
57 return ''
58 } else {
59 return '\n'
60 }
61}
62
63function compareLongText (snapshotValue, value, json) {
64 if (snapshotValue === value) {
65 return Result.Ok()
66 }
67
68 const textDiff = textDifference(snapshotValue, value, true)
69
70 if (json) {
71 return Result.Error({
72 message: textDiff,
73 expected: snapshotValue,
74 value
75 })
76 }
77
78 const diff =
79 '\n' +
80 header('Difference') +
81 textDiff +
82 maybeEndNewLine(textDiff) +
83 header('Saved snapshot text') +
84 snapshotValue +
85 maybeEndNewLine(snapshotValue) +
86 header('Current text') +
87 value +
88 maybeEndNewLine(value) +
89 header('Diff end')
90
91 return Result.Error(diff)
92}
93
94const raise = () => {
95 throw new Error('should not happen')
96}
97
98const isUndefined = x => {
99 la(is.not.defined(x))
100}
101
102const asResult = x => Result.of(x)
103
104// eslint-disable-next-line immutable/no-mutation
105module.exports = {
106 raise,
107 isUndefined,
108 asResult,
109 compareText,
110 compareLongText,
111 textDifference
112}