-
Notifications
You must be signed in to change notification settings - Fork 28.2k
/
Copy pathindex.test.ts
91 lines (79 loc) · 2.45 KB
/
index.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
import { createNext } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { fetchViaHTTP } from 'next-test-utils'
describe('Middleware fetches with any HTTP method', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
'pages/api/ping.js': `
export default (req, res) => {
res.send(JSON.stringify({
method: req.method,
headers: {...req.headers},
}))
}
`,
'middleware.js': `
import { NextResponse } from 'next/server';
const HTTP_ECHO_URL = 'https://http-echo-kou029w.vercel.app/';
export default async (req) => {
const kind = req.nextUrl.searchParams.get('kind')
const handler = handlers[kind] ?? handlers['normal-fetch'];
const response = await handler({url: HTTP_ECHO_URL, method: req.method});
const json = await response.text()
const res = NextResponse.next();
res.headers.set('x-resolved', json ?? '{}');
return res
}
const handlers = {
'new-request': ({url, method}) =>
fetch(new Request(url, { method, headers: { 'x-kind': 'new-request' } })),
'normal-fetch': ({url, method}) =>
fetch(url, { method, headers: { 'x-kind': 'normal-fetch' } })
}
`,
},
dependencies: {},
})
})
afterAll(() => next.destroy())
it('passes the method on a direct fetch request', async () => {
const response = await fetchViaHTTP(
next.url,
'/api/ping',
{},
{ method: 'POST' }
)
const json = await response.json()
expect(json).toMatchObject({
method: 'POST',
})
const headerJson = JSON.parse(response.headers.get('x-resolved'))
expect(headerJson).toMatchObject({
method: 'POST',
headers: {
'x-kind': 'normal-fetch',
},
})
})
it('passes the method when providing a Request object', async () => {
const response = await fetchViaHTTP(
next.url,
'/api/ping',
{ kind: 'new-request' },
{ method: 'POST' }
)
const json = await response.json()
expect(json).toMatchObject({
method: 'POST',
})
const headerJson = JSON.parse(response.headers.get('x-resolved'))
expect(headerJson).toMatchObject({
method: 'POST',
headers: {
'x-kind': 'new-request',
},
})
})
})