UNPKG

939 BJavaScriptView Raw
1'use strict'
2
3const diff = require('variable-diff')
4const disparity = require('disparity')
5const is = require('check-more-types')
6
7const isMultiLineText = s => is.string(s) && s.includes('\n')
8const areStrings = (s, t) => is.string(s) && is.string(t)
9const compareAsStrings = (s, t) => areStrings(s, t) &&
10 (isMultiLineText(s) || isMultiLineText(t))
11
12function compareText (expected, value) {
13 const textDiff = disparity.unified(expected, value)
14 if (!textDiff) {
15 return {changed: false}
16 }
17 return {
18 changed: true,
19 text: textDiff
20 }
21}
22
23const compareObjects = diff
24
25function compare ({expected, value}) {
26 const diffed = compareAsStrings(value, expected)
27 ? compareText(expected + '\n', value + '\n')
28 : compareObjects(expected, value)
29 if (diffed.changed) {
30 return {
31 valid: false,
32 message: `snapshot difference\n${diffed.text}`
33 }
34 }
35 return {
36 valid: true
37 }
38}
39
40module.exports = compare