-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmock_fetch.mjs
74 lines (58 loc) · 1.73 KB
/
mock_fetch.mjs
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
import assert from "node:assert"
export class MockFetch {
constructor() {
this.requests = []
}
addExpectedRequest({ body, headers = {}, method, response, url }) {
this.requests.push({ body, fulfilled: false, headers, method, response, url })
return this
}
delete(options) {
return this.addExpectedRequest({ ...options, method: 'delete' })
}
get(options) {
return this.addExpectedRequest({ ...options, method: 'get' })
}
post(options) {
return this.addExpectedRequest({ ...options, method: 'post' })
}
put(options) {
return this.addExpectedRequest({ ...options, method: 'put' })
}
get fetcher() {
// eslint-disable-next-line require-await
return async (...args) => {
const [url, options] = args
const headers = options?.headers
const urlString = url.toString()
const match = this.requests.find(
(request) =>
request.method.toLowerCase() === options?.method.toLowerCase() &&
request.url === urlString &&
!request.fulfilled,
)
if (!match) {
throw new Error(`Unexpected fetch call: ${url}`)
}
for (const key in match.headers) {
assert.equal(headers[key], match.headers[key])
}
if (typeof match.body === 'string') {
assert.equal(options?.body, match.body)
} else if (typeof match.body === 'function') {
const bodyFn = match.body
bodyFn(options?.body)
} else {
assert.equal(options?.body, undefined)
}
match.fulfilled = true
if (match.response instanceof Error) {
throw match.response
}
return match.response
}
}
get fulfilled() {
return this.requests.every((request) => request.fulfilled)
}
}