1 | 'use strict'
|
2 |
|
3 | const diff = require('variable-diff')
|
4 | const disparity = require('disparity')
|
5 | const is = require('check-more-types')
|
6 |
|
7 | const isMultiLineText = s => is.string(s) && s.includes('\n')
|
8 | const areStrings = (s, t) => is.string(s) && is.string(t)
|
9 | const compareAsStrings = (s, t) => areStrings(s, t) &&
|
10 | (isMultiLineText(s) || isMultiLineText(t))
|
11 |
|
12 | function 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 |
|
23 | const compareObjects = diff
|
24 |
|
25 | function 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 |
|
40 | module.exports = compare
|