« get me outta code hell

strict-match-error.js « lib « test - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/test/lib/strict-match-error.js
blob: e3b36e93a0be10d5de504f136e9105edfa614843 (plain)
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
export function strictlyThrows(t, fn, pattern) {
  const error = catchErrorOrNull(fn);

  t.currentAssert = strictlyThrows;

  if (error === null) {
    t.fail(`expected to throw`);
    return;
  }

  const nameAndMessage = `${pattern.constructor.name} ${pattern.message}`;
  t.match(
    prepareErrorForMatch(error),
    prepareErrorForMatch(pattern),
    (pattern instanceof AggregateError
      ? `expected to throw: ${nameAndMessage} (${pattern.errors.length} error(s))`
      : `expected to throw: ${nameAndMessage}`));
}

function prepareErrorForMatch(error) {
  if (error instanceof RegExp) {
    return {
      message: error,
    };
  }

  if (!(error instanceof Error)) {
    return error;
  }

  const matchable = {
    name: error.constructor.name,
    message: error.message,
  };

  if (error instanceof AggregateError) {
    matchable.errors = error.errors.map(prepareErrorForMatch);
  }

  return matchable;
}

function catchErrorOrNull(fn) {
  try {
    fn();
    return null;
  } catch (error) {
    return error;
  }
}