-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathexpectJSON.ts
51 lines (42 loc) · 1.2 KB
/
expectJSON.ts
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
import { expect } from 'chai';
import { isObjectLike } from '../jsutils/isObjectLike.js';
import { mapValue } from '../jsutils/mapValue.js';
/**
* Deeply transforms an arbitrary value to a JSON-safe value by calling toJSON
* on any nested value which defines it.
*/
function toJSONDeep(value: unknown): unknown {
if (!isObjectLike(value)) {
return value;
}
if (typeof value.toJSON === 'function') {
return value.toJSON();
}
if (Array.isArray(value)) {
return value.map(toJSONDeep);
}
return mapValue(value, toJSONDeep);
}
export function expectJSON(actual: unknown) {
const actualJSON = toJSONDeep(actual);
return {
toDeepEqual(expected: unknown) {
const expectedJSON = toJSONDeep(expected);
expect(actualJSON).to.deep.equal(expectedJSON);
},
toDeepNestedProperty(path: string, expected: unknown) {
const expectedJSON = toJSONDeep(expected);
expect(actualJSON).to.deep.nested.property(path, expectedJSON);
},
};
}
export function expectToThrowJSON(fn: () => unknown) {
function mapException(): unknown {
try {
return fn();
} catch (error) {
throw toJSONDeep(error);
}
}
return expect(mapException).to.throw();
}