-
-
Notifications
You must be signed in to change notification settings - Fork 469
/
http.test.ts
75 lines (65 loc) · 1.9 KB
/
http.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
/**
* @jest-environment node
*/
/**
* @note Do not import as wildcard lest the ESM gods be displeased.
* Make sure "allowSyntheticDefaultImports" is true in tsconfig.json.
*/
import http from 'http'
import { ServerApi, createServer } from '@open-draft/test-server'
import { rest } from 'msw'
import { setupServer } from 'msw/node'
import { waitForClientRequest } from '../../../support/utils'
let httpServer: ServerApi
const server = setupServer()
beforeAll(async () => {
server.listen()
httpServer = await createServer((app) => {
app.get('/resource', (_, res) => {
return res.status(500).send('original-response')
})
})
})
beforeEach(() => {
server.use(
rest.get(httpServer.http.makeUrl('/resource'), (req, res, ctx) => {
return res(
ctx.status(401),
ctx.set('x-header', 'yes'),
ctx.json({ firstName: 'John' }),
)
}),
)
})
afterEach(() => {
server.resetHandlers()
})
afterAll(async () => {
server.close()
await httpServer.close()
})
it('returns a mocked response to an "http.get" request', async () => {
const request = http.get(httpServer.http.makeUrl('/resource'))
const { response, responseText } = await waitForClientRequest(request)
expect(response.statusCode).toBe(401)
expect(response.headers).toEqual(
expect.objectContaining({
'content-type': 'application/json',
'x-header': 'yes',
}),
)
expect(responseText).toBe('{"firstName":"John"}')
})
it('returns a mocked response to an "http.request" request', async () => {
const request = http.request(httpServer.http.makeUrl('/resource'))
request.end()
const { response, responseText } = await waitForClientRequest(request)
expect(response.statusCode).toBe(401)
expect(response.headers).toEqual(
expect.objectContaining({
'content-type': 'application/json',
'x-header': 'yes',
}),
)
expect(responseText).toBe('{"firstName":"John"}')
})