printSnapshot.js 10.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.printSnapshotAndReceived =
  exports.printReceived =
  exports.printPropertiesAndReceived =
  exports.printExpected =
  exports.noColor =
  exports.matcherHintFromConfig =
  exports.getSnapshotColorForChalkInstance =
  exports.getReceivedColorForChalkInstance =
  exports.bReceivedColor =
  exports.aSnapshotColor =
  exports.SNAPSHOT_ARG =
  exports.PROPERTIES_ARG =
  exports.HINT_ARG =
    void 0;

var _chalk = _interopRequireDefault(require('chalk'));

var _utils = require('expect/build/utils');

var _jestDiff = require('jest-diff');

var _jestGetType = require('jest-get-type');

var _jestMatcherUtils = require('jest-matcher-utils');

var _prettyFormat = require('pretty-format');

var _colors = require('./colors');

var _dedentLines = require('./dedentLines');

var _utils2 = require('./utils');

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {default: obj};
}

/**
 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/* eslint-disable local/ban-types-eventually */
// Temporary hack because getObjectSubset has known limitations,
// is not in the public interface of the expect package,
// and the long-term goal is to use a non-serialization diff.
// Make sure to remove file from `exports` in `expect/package.json`.
const getSnapshotColorForChalkInstance = chalkInstance => {
  const level = chalkInstance.level;

  if (level === 3) {
    return chalkInstance
      .rgb(
        _colors.aForeground3[0],
        _colors.aForeground3[1],
        _colors.aForeground3[2]
      )
      .bgRgb(
        _colors.aBackground3[0],
        _colors.aBackground3[1],
        _colors.aBackground3[2]
      );
  }

  if (level === 2) {
    return chalkInstance
      .ansi256(_colors.aForeground2)
      .bgAnsi256(_colors.aBackground2);
  }

  return chalkInstance.magenta.bgYellowBright;
};

exports.getSnapshotColorForChalkInstance = getSnapshotColorForChalkInstance;

const getReceivedColorForChalkInstance = chalkInstance => {
  const level = chalkInstance.level;

  if (level === 3) {
    return chalkInstance
      .rgb(
        _colors.bForeground3[0],
        _colors.bForeground3[1],
        _colors.bForeground3[2]
      )
      .bgRgb(
        _colors.bBackground3[0],
        _colors.bBackground3[1],
        _colors.bBackground3[2]
      );
  }

  if (level === 2) {
    return chalkInstance
      .ansi256(_colors.bForeground2)
      .bgAnsi256(_colors.bBackground2);
  }

  return chalkInstance.cyan.bgWhiteBright; // also known as teal
};

exports.getReceivedColorForChalkInstance = getReceivedColorForChalkInstance;
const aSnapshotColor = getSnapshotColorForChalkInstance(_chalk.default);
exports.aSnapshotColor = aSnapshotColor;
const bReceivedColor = getReceivedColorForChalkInstance(_chalk.default);
exports.bReceivedColor = bReceivedColor;

const noColor = string => string;

exports.noColor = noColor;
const HINT_ARG = 'hint';
exports.HINT_ARG = HINT_ARG;
const SNAPSHOT_ARG = 'snapshot';
exports.SNAPSHOT_ARG = SNAPSHOT_ARG;
const PROPERTIES_ARG = 'properties';
exports.PROPERTIES_ARG = PROPERTIES_ARG;

const matcherHintFromConfig = (
  {context: {isNot, promise}, hint, inlineSnapshot, matcherName, properties},
  isUpdatable
) => {
  const options = {
    isNot,
    promise
  };

  if (isUpdatable) {
    options.receivedColor = bReceivedColor;
  }

  let expectedArgument = '';

  if (typeof properties === 'object') {
    expectedArgument = PROPERTIES_ARG;

    if (isUpdatable) {
      options.expectedColor = noColor;
    }

    if (typeof hint === 'string' && hint.length !== 0) {
      options.secondArgument = HINT_ARG;
      options.secondArgumentColor = _jestMatcherUtils.BOLD_WEIGHT;
    } else if (typeof inlineSnapshot === 'string') {
      options.secondArgument = SNAPSHOT_ARG;

      if (isUpdatable) {
        options.secondArgumentColor = aSnapshotColor;
      } else {
        options.secondArgumentColor = noColor;
      }
    }
  } else {
    if (typeof hint === 'string' && hint.length !== 0) {
      expectedArgument = HINT_ARG;
      options.expectedColor = _jestMatcherUtils.BOLD_WEIGHT;
    } else if (typeof inlineSnapshot === 'string') {
      expectedArgument = SNAPSHOT_ARG;

      if (isUpdatable) {
        options.expectedColor = aSnapshotColor;
      }
    }
  }

  return (0, _jestMatcherUtils.matcherHint)(
    matcherName,
    undefined,
    expectedArgument,
    options
  );
}; // Given array of diffs, return string:
// * include common substrings
// * exclude change substrings which have opposite op
// * include change substrings which have argument op
//   with change color only if there is a common substring

exports.matcherHintFromConfig = matcherHintFromConfig;

const joinDiffs = (diffs, op, hasCommon) =>
  diffs.reduce(
    (reduced, diff) =>
      reduced +
      (diff[0] === _jestDiff.DIFF_EQUAL
        ? diff[1]
        : diff[0] !== op
        ? ''
        : hasCommon
        ? (0, _jestMatcherUtils.INVERTED_COLOR)(diff[1])
        : diff[1]),
    ''
  );

const isLineDiffable = received => {
  const receivedType = (0, _jestGetType.getType)(received);

  if ((0, _jestGetType.isPrimitive)(received)) {
    return typeof received === 'string';
  }

  if (
    receivedType === 'date' ||
    receivedType === 'function' ||
    receivedType === 'regexp'
  ) {
    return false;
  }

  if (received instanceof Error) {
    return false;
  }

  if (
    receivedType === 'object' &&
    typeof received.asymmetricMatch === 'function'
  ) {
    return false;
  }

  return true;
};

const printExpected = val =>
  (0, _jestMatcherUtils.EXPECTED_COLOR)((0, _utils2.minify)(val));

exports.printExpected = printExpected;

const printReceived = val =>
  (0, _jestMatcherUtils.RECEIVED_COLOR)((0, _utils2.minify)(val));

exports.printReceived = printReceived;

const printPropertiesAndReceived = (
  properties,
  received,
  expand // CLI options: true if `--expand` or false if `--no-expand`
) => {
  const aAnnotation = 'Expected properties';
  const bAnnotation = 'Received value';

  if (isLineDiffable(properties) && isLineDiffable(received)) {
    return (0, _jestDiff.diffLinesUnified)(
      (0, _utils2.serialize)(properties).split('\n'),
      (0, _utils2.serialize)(
        (0, _utils.getObjectSubset)(received, properties)
      ).split('\n'),
      {
        aAnnotation,
        aColor: _jestMatcherUtils.EXPECTED_COLOR,
        bAnnotation,
        bColor: _jestMatcherUtils.RECEIVED_COLOR,
        changeLineTrailingSpaceColor: _chalk.default.bgYellow,
        commonLineTrailingSpaceColor: _chalk.default.bgYellow,
        emptyFirstOrLastLinePlaceholder: '↵',
        // U+21B5
        expand,
        includeChangeCounts: true
      }
    );
  }

  const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(
    aAnnotation,
    bAnnotation
  );
  return (
    printLabel(aAnnotation) +
    printExpected(properties) +
    '\n' +
    printLabel(bAnnotation) +
    printReceived(received)
  );
};

exports.printPropertiesAndReceived = printPropertiesAndReceived;
const MAX_DIFF_STRING_LENGTH = 20000;

const printSnapshotAndReceived = (
  a,
  b,
  received,
  expand // CLI options: true if `--expand` or false if `--no-expand`
) => {
  const aAnnotation = 'Snapshot';
  const bAnnotation = 'Received';
  const aColor = aSnapshotColor;
  const bColor = bReceivedColor;
  const options = {
    aAnnotation,
    aColor,
    bAnnotation,
    bColor,
    changeLineTrailingSpaceColor: noColor,
    commonLineTrailingSpaceColor: _chalk.default.bgYellow,
    emptyFirstOrLastLinePlaceholder: '↵',
    // U+21B5
    expand,
    includeChangeCounts: true
  };

  if (typeof received === 'string') {
    if (
      a.length >= 2 &&
      a.startsWith('"') &&
      a.endsWith('"') &&
      b === (0, _prettyFormat.format)(received)
    ) {
      // If snapshot looks like default serialization of a string
      // and received is string which has default serialization.
      if (!a.includes('\n') && !b.includes('\n')) {
        // If neither string is multiline,
        // display as labels and quoted strings.
        let aQuoted = a;
        let bQuoted = b;

        if (
          a.length - 2 <= MAX_DIFF_STRING_LENGTH &&
          b.length - 2 <= MAX_DIFF_STRING_LENGTH
        ) {
          const diffs = (0, _jestDiff.diffStringsRaw)(
            a.slice(1, -1),
            b.slice(1, -1),
            true
          );
          const hasCommon = diffs.some(
            diff => diff[0] === _jestDiff.DIFF_EQUAL
          );
          aQuoted =
            '"' + joinDiffs(diffs, _jestDiff.DIFF_DELETE, hasCommon) + '"';
          bQuoted =
            '"' + joinDiffs(diffs, _jestDiff.DIFF_INSERT, hasCommon) + '"';
        }

        const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(
          aAnnotation,
          bAnnotation
        );
        return (
          printLabel(aAnnotation) +
          aColor(aQuoted) +
          '\n' +
          printLabel(bAnnotation) +
          bColor(bQuoted)
        );
      } // Else either string is multiline, so display as unquoted strings.

      a = (0, _utils2.deserializeString)(a); //  hypothetical expected string

      b = received; // not serialized
    } // Else expected had custom serialization or was not a string
    // or received has custom serialization.

    return a.length <= MAX_DIFF_STRING_LENGTH &&
      b.length <= MAX_DIFF_STRING_LENGTH
      ? (0, _jestDiff.diffStringsUnified)(a, b, options)
      : (0, _jestDiff.diffLinesUnified)(a.split('\n'), b.split('\n'), options);
  }

  if (isLineDiffable(received)) {
    const aLines2 = a.split('\n');
    const bLines2 = b.split('\n'); // Fall through to fix a regression for custom serializers
    // like jest-snapshot-serializer-raw that ignore the indent option.

    const b0 = (0, _utils2.serialize)(received, 0);

    if (b0 !== b) {
      const aLines0 = (0, _dedentLines.dedentLines)(aLines2);

      if (aLines0 !== null) {
        // Compare lines without indentation.
        const bLines0 = b0.split('\n');
        return (0, _jestDiff.diffLinesUnified2)(
          aLines2,
          bLines2,
          aLines0,
          bLines0,
          options
        );
      }
    } // Fall back because:
    // * props include a multiline string
    // * text has more than one adjacent line
    // * markup does not close

    return (0, _jestDiff.diffLinesUnified)(aLines2, bLines2, options);
  }

  const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(
    aAnnotation,
    bAnnotation
  );
  return (
    printLabel(aAnnotation) +
    aColor(a) +
    '\n' +
    printLabel(bAnnotation) +
    bColor(b)
  );
};

exports.printSnapshotAndReceived = printSnapshotAndReceived;