1 | 'use strict'
|
2 |
|
3 | const diff = require('variable-diff')
|
4 | const is = require('check-more-types')
|
5 | const utils = require('./utils')
|
6 | const Result = require('folktale/result')
|
7 | const stripAnsi = require('strip-ansi')
|
8 | const debug = require('debug')('snap-shot-compare')
|
9 |
|
10 | const isMultiLineText = s => is.string(s) && s.includes('\n')
|
11 | const areStrings = (s, t) => is.string(s) && is.string(t)
|
12 | const compareAsStrings = (s, t) =>
|
13 | areStrings(s, t) && (isMultiLineText(s) || isMultiLineText(t))
|
14 |
|
15 |
|
16 | const isLong = s => s.split('\n').length > 9
|
17 |
|
18 | const diffAsLongText = (s, t) =>
|
19 | compareAsStrings(s, t) && (isLong(s) || isLong(t))
|
20 |
|
21 | const compareObjects = diff
|
22 |
|
23 | function compare ({ expected, value, json, noColor }) {
|
24 | if (compareAsStrings(value, expected)) {
|
25 | if (diffAsLongText(value, expected)) {
|
26 | debug('compare as long text')
|
27 | return utils.compareLongText(expected, value, json)
|
28 | } else {
|
29 | debug('compare as normal text')
|
30 | debug('expected')
|
31 | debug(expected)
|
32 | debug('current value')
|
33 | debug(value)
|
34 | return utils.compareText(expected, value, noColor, json)
|
35 | }
|
36 | }
|
37 |
|
38 | debug('comparing objects')
|
39 | const diffed = compareObjects(expected, value)
|
40 | if (!diffed.changed) {
|
41 | return Result.Ok()
|
42 | }
|
43 |
|
44 | if (json) {
|
45 | noColor = true
|
46 | }
|
47 |
|
48 | const diffText = noColor ? stripAnsi(diffed.text) : diffed.text
|
49 |
|
50 | if (json) {
|
51 | return Result.Error({
|
52 | message: diffText,
|
53 | expected,
|
54 | value
|
55 | })
|
56 | }
|
57 | return Result.Error(diffText)
|
58 | }
|
59 |
|
60 |
|
61 | module.exports = compare
|