-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
chai.ts
61 lines (55 loc) · 1.71 KB
/
chai.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
import type { ChaiPlugin } from '../chai/types'
import { SnapshotClient } from './client'
let _client: SnapshotClient
export function getSnapshotClient(): SnapshotClient {
if (!_client)
_client = new SnapshotClient()
return _client
}
const getErrorString = (expected: () => void) => {
try {
expected()
}
catch (e) {
if (e instanceof Error)
return e.message
return e
}
throw new Error('snapshot function didn\'t threw')
}
export const SnapshotPlugin: ChaiPlugin = (chai, utils) => {
for (const key of ['matchSnapshot', 'toMatchSnapshot']) {
utils.addMethod(
chai.Assertion.prototype,
key,
function(this: Record<string, unknown>, message?: string) {
const expected = utils.flag(this, 'object')
getSnapshotClient().assert(expected, message)
},
)
}
utils.addMethod(
chai.Assertion.prototype,
'toMatchInlineSnapshot',
function(this: Record<string, unknown>, inlineSnapshot: string, message: string) {
const expected = utils.flag(this, 'object')
getSnapshotClient().assert(expected, message, true, inlineSnapshot)
},
)
utils.addMethod(
chai.Assertion.prototype,
'toThrowErrorMatchingSnapshot',
function(this: Record<string, unknown>, message?: string) {
const expected = utils.flag(this, 'object')
getSnapshotClient().assert(getErrorString(expected), message)
},
)
utils.addMethod(
chai.Assertion.prototype,
'toThrowErrorMatchingInlineSnapshot',
function(this: Record<string, unknown>, inlineSnapshot: string, message: string) {
const expected = utils.flag(this, 'object')
getSnapshotClient().assert(getErrorString(expected), message, true, inlineSnapshot)
},
)
}