-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
76 lines (66 loc) · 2.2 KB
/
index.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
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
import { MatcherState, ExpectationResult, SyncExpectationResult } from 'expect/build/types'
import matchers from 'expect/build/matchers'
declare global {
namespace jest {
interface Matchers<R> {
toBeJSON(): R;
toEqualJSON(b: any): R;
toMatchJSON(b: any): R;
}
interface Expect {
jsonContaining<E = {}>(b: E): any;
}
}
}
export function toBeJSON(this: MatcherState, received: unknown): SyncExpectationResult {
if (typeof received !== 'string') {
return {
pass: false,
message: () => [
'expected',
this.utils.printReceived(received),
'to be JSON, but it is not a',
this.utils.EXPECTED_COLOR('JSON string')
].join(' ')
}
}
try {
JSON.parse(received)
return {
pass: true,
message: () => [
'expected',
this.utils.printReceived(received),
'not to be JSON, but it is a',
this.utils.EXPECTED_COLOR('JSON string')
].join(' ')
}
} catch (e) {
return {
pass: false,
message: () => [
'expected',
this.utils.printReceived(received),
'to be JSON, but it is not a',
this.utils.EXPECTED_COLOR('valid JSON string')
].join(' ')
}
}
}
export function toEqualJSON(this: MatcherState, received: unknown, jsonObject: any): ExpectationResult {
var isJSON = toBeJSON.call(this, received)
if (!isJSON.pass) {
return isJSON
}
return matchers.toEqual.call(this, JSON.parse(received as string), jsonObject)
}
export function toMatchJSON(this: MatcherState, received: unknown, jsonObject: any): ExpectationResult {
var isJSON = toBeJSON.call(this, received)
if (!isJSON.pass) {
return isJSON
}
return matchers.toMatchObject.call(this, JSON.parse(received as string), jsonObject)
}
export function jsonContaining(received: unknown, jsonObject: any): ExpectationResult {
return toMatchJSON.call(expect.getState() as MatcherState, received, jsonObject)
}