All files / src/tests test-util.js

100% Statements 32/32
100% Branches 15/15
100% Functions 12/12
100% Lines 27/27
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 728x     21x 21x 80x 80x         11x 11x 11x       22x 20x 16x       20x 20x       23x 23x         82x 82x             164x 21x 21x 63x 42x 42x         314x 311x       82x             8x              
const assert = require("assert");
 
function errorToJson(e) {
  const props = Object.getOwnPropertyNames(e).concat("name");
  return props.reduce((p, c) => {
    p[c] = e[c];
    return p;
  }, {});
}
 
function expectErrorEquality(e1, e2) {
  const ne1 = normalizeErrorForEquality(e1);
  const ne2 = normalizeErrorForEquality(e2);
  expect(ne1).toEqual(ne2);
}
 
function normalizeErrorForEquality(e) {
  if (!e) return e;
  if (typeof e === "string") return omitStack(errorToJson(new Error(e)));
  return omitStack(errorToJson(e));
}
 
function omitStack(s) {
  delete s.stack;
  return s;
}
 
function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}
 
function deepEqual(actual, expected) {
  const a = normalizeError(actual);
  const e = normalizeError(expected);
  // istanbul ignore next
  if (usingJest()) expect(a).toEqual(e);
  else assert.deepEqual(a, e);
}
 
function normalizeError(v) {
  if (!isError(v)) return v;
  const props = Object.getOwnPropertyNames(v).concat("name");
  return props.reduce((p, c) => {
    if (c === "stack") return p;
    p[c] = v[c];
    return p;
  }, {});
}
 
function isError(e) {
  if (!e) return false;
  return e instanceof Error || e.code === "ERR_ASSERTION";
}
 
function usingJest() {
  return (
    typeof expect !== "undefined" &&
    Boolean(expect.extend) &&
    Boolean(expect.anything)
  );
}
 
module.exports = {
  errorToJson,
  expectErrorEquality,
  sleep,
  deepEqual,
  isError
};