-
-
Notifications
You must be signed in to change notification settings - Fork 469
/
delay.node.test.ts
71 lines (56 loc) · 1.78 KB
/
delay.node.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
/**
* @jest-environment node
*/
import fetch from 'node-fetch'
import { rest } from 'msw'
import { setupServer } from 'msw/node'
import { performance } from 'perf_hooks'
const server = setupServer()
beforeAll(() => {
server.listen()
})
afterEach(() => {
server.resetHandlers()
})
afterAll(() => {
server.close()
})
async function makeRequest(url: string) {
const requestStart = performance.now()
const res = await fetch(url)
const requestEnd = performance.now()
const responseTime = requestEnd - requestStart
return { res, responseTime }
}
test('uses explicit server response time', async () => {
server.use(
rest.get('http://localhost/user', (req, res, ctx) => {
return res(ctx.delay(500), ctx.text('john'))
}),
)
const { res, responseTime } = await makeRequest('http://localhost/user')
expect(responseTime).toBeGreaterThanOrEqual(500)
expect(await res.text()).toBe('john')
})
test('uses realistic server response time when no duration is provided', async () => {
server.use(
rest.get('http://localhost/user', (req, res, ctx) => {
return res(ctx.delay(), ctx.text('john'))
}),
)
const { res, responseTime } = await makeRequest('http://localhost/user')
// Realistic server response time in Node.js is set to 5ms.
expect(responseTime).toBeGreaterThan(5)
expect(await res.text()).toBe('john')
})
test('uses realistic server response time when "real" mode is provided', async () => {
server.use(
rest.get('http://localhost/user', (req, res, ctx) => {
return res(ctx.delay('real'), ctx.text('john'))
}),
)
const { res, responseTime } = await makeRequest('http://localhost/user')
// Realistic server response time in Node.js is set to 5ms.
expect(responseTime).toBeGreaterThan(5)
expect(await res.text()).toBe('john')
})