-
Notifications
You must be signed in to change notification settings - Fork 0
/
assert-equals.js
49 lines (39 loc) · 1.32 KB
/
assert-equals.js
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
function assertEquals (expected, actual, message) {
try {
deepEquals(expected, actual);
}
catch (failure) {
throw (`${message ? message + ' ' : ''}${failure.message}`);
}
};
function deepEquals (a, b, trace='') {
let typeA = getType(a), typeB = getType(b);
if (typeA === 'undefined' && typeB !== 'undefined')
throw {message: `Found ${trace}, none expected`};
if (typeB === 'undefined' && typeA !== 'undefined')
throw {message: `Expected ${trace}, but was not found`};
if (typeA !== typeB)
throw {message: `Expected type ${getType(a)}, but found type ${getType(b)}`};
if (typeof a !== 'object' && a !== b)
throw {message: `Expected ${trace ? trace + " " : ""}${JSON.stringify(a)}, but found ${JSON.stringify(b)}`};
if (typeA === 'array' && a.length !== b.length)
throw {message: `Expected array length ${a.length}, but found ${b.length}`};
if (typeof a === 'object')
([...Object.keys(a), ...Object.keys(b)]).forEach(
key => deepEquals(a[key], b[key], `${trace}${buildTrace(a, key)}`)
);
};
function getType(x) {
if (x === null)
return 'null';
if (x instanceof Array)
return 'array';
return typeof x;
};
function buildTrace (element, key) {
if (element instanceof Array)
return `[${key}]`
else
return `.${key}`
};
module.exports = assertEquals;