forked from hplush/slowreader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.test.ts
101 lines (80 loc) · 2.59 KB
/
request.test.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { deepStrictEqual, equal, rejects, throws } from 'node:assert'
import { afterEach, test } from 'node:test'
import { setTimeout } from 'node:timers/promises'
import {
checkAndRemoveRequestMock,
expectRequest,
mockRequest,
request,
setRequestMethod
} from '../index.ts'
afterEach(() => {
setRequestMethod(fetch)
})
test('replaces request method', () => {
let result = new Promise<Response>(resolve => {
resolve(new Response())
})
let calls: string[] = []
setRequestMethod(url => {
if (typeof url === 'string') {
calls.push(url)
}
return result
})
equal(request('https://example.com'), result)
deepStrictEqual(calls, ['https://example.com'])
})
test('checks that all mock requests was called', async () => {
mockRequest()
expectRequest('https://one.com').andRespond(200)
expectRequest('https://two.com').andRespond(200)
equal((await request('https://one.com')).status, 200)
throws(() => {
checkAndRemoveRequestMock()
}, /didn’t send requests: https:\/\/two.com/)
})
test('checks mocks order', async () => {
mockRequest()
expectRequest('https://one.com').andRespond(200)
expectRequest('https://two.com').andRespond(200)
await rejects(
request('https://two.com'),
/https:\/\/one\.com instead of https:\/\/two\.com/
)
})
test('is ready for unexpected requests', async () => {
mockRequest()
expectRequest('https://one.com').andRespond(200)
equal((await request('https://one.com')).status, 200)
await rejects(
request('https://one.com'),
/Unexpected request https:\/\/one.com/
)
})
test('marks requests as aborted', async () => {
mockRequest()
let reply = expectRequest('https://one.com').andWait()
let aborted = ''
let controller = new AbortController()
request('https://one.com', { signal: controller.signal }).catch(e => {
if (e instanceof Error) aborted = e.name
})
controller.abort()
await setTimeout(10)
equal(aborted, 'AbortError')
equal(reply.aborted, true)
})
test('sets content type', async () => {
mockRequest()
expectRequest('https://one.com').andRespond(200, 'Hi')
let response1 = await request('https://one.com')
equal(response1.headers.get('content-type'), 'text/html')
expectRequest('https://two.com').andRespond(200, 'Hi', 'text/plain')
let response2 = await request('https://two.com')
equal(response2.headers.get('content-type'), 'text/plain')
let reply3 = expectRequest('https://two.com').andWait()
reply3(200, 'Hi', 'text/html; charset=utf-8')
let response3 = await request('https://two.com')
equal(response3.headers.get('content-type'), 'text/html; charset=utf-8')
})