UNPKG

1.57 kBJavaScriptView Raw
1'use strict'
2
3const diff = require('variable-diff')
4const is = require('check-more-types')
5const utils = require('./utils')
6const Result = require('folktale/result')
7const stripAnsi = require('strip-ansi')
8const debug = require('debug')('snap-shot-compare')
9
10const isMultiLineText = s => is.string(s) && s.includes('\n')
11const areStrings = (s, t) => is.string(s) && is.string(t)
12const compareAsStrings = (s, t) =>
13 areStrings(s, t) && (isMultiLineText(s) || isMultiLineText(t))
14
15// looks at number of lines
16const isLong = s => s.split('\n').length > 9
17
18const diffAsLongText = (s, t) =>
19 compareAsStrings(s, t) && (isLong(s) || isLong(t))
20
21const compareObjects = diff
22
23function 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// eslint-disable-next-line immutable/no-mutation
61module.exports = compare