-
Notifications
You must be signed in to change notification settings - Fork 49
/
ApiMock.js
87 lines (77 loc) · 1.88 KB
/
ApiMock.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
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
77
78
79
80
81
82
83
84
85
86
87
function mockPromiseResolving (value) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
clearTimeout(timer)
resolve(value)
}, 100)
})
}
class MockStubbing {
constructor (fieldName, value) {
this._fieldName = fieldName
this._value = value
}
forFieldName (fieldName) {
this._fieldName = fieldName
return this
}
get fieldName () {
return this._fieldName
}
get value () {
return this._value
}
}
class ApiMockState {
constructor () {
this._get = jest.fn()
this._patch = jest.fn()
}
getMocks () {
return {
get: this._get,
patch: this._patch
}
}
get () {
const apiMock = this
return {
thenReturn (mockStubbing) {
if (!(mockStubbing instanceof MockStubbing)) {
throw new Error('apiMock must be instance of MockStubbing')
}
if (mockStubbing.fieldName === undefined || mockStubbing.value === undefined) {
throw new Error('fieldName and value must be defined')
}
apiMock._get.mockReturnValue({
[mockStubbing.fieldName]: mockStubbing.value,
_meta: {
load: Promise.resolve(mockStubbing.value)
}
})
}
}
}
patch () {
const apiMock = this
return {
thenReturn (mockStubbing) {
if (!(mockStubbing instanceof MockStubbing)) {
throw new Error('apiMock must be instance of MockStubbing')
}
if (mockStubbing.fieldName !== undefined || mockStubbing.value === undefined) {
throw new Error('fieldName must be undefined and value must be defined')
}
apiMock._patch.mockReturnValue(mockPromiseResolving(mockStubbing.value))
}
}
}
}
export class ApiMock {
static create () {
return new ApiMockState()
}
static success (value) {
return new MockStubbing(undefined, value)
}
}