-
Notifications
You must be signed in to change notification settings - Fork 26.1k
/
index.test.js
91 lines (77 loc) · 2.02 KB
/
index.test.js
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
/* eslint-env jest */
import { join } from 'path'
import {
killApp,
findPort,
launchApp,
fetchViaHTTP,
initNextServerScript,
} from 'next-test-utils'
import clone from 'clone'
import getPort from 'get-port'
jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../')
let appPort
let app
let server
jest.setTimeout(1000 * 60 * 2)
const context = {}
function runTests() {
it('should parse JSON body', async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort, {})
const data = await makeRequest()
expect(data).toEqual([{ title: 'Nextjs' }])
killApp(app)
})
it('should not throw if request body is already parsed in custom middleware', async () => {
await startServer()
const data = await makeRequest()
expect(data).toEqual([{ title: 'Nextjs' }])
killApp(server)
})
it("should not throw if request's content-type is invalid", async () => {
await startServer()
const status = await makeRequestWithInvalidContentType()
expect(status).toBe(200)
killApp(server)
})
}
async function makeRequest() {
const data = await fetchViaHTTP(appPort, '/api', null, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify([{ title: 'Nextjs' }]),
}).then((res) => res.ok && res.json())
return data
}
async function makeRequestWithInvalidContentType() {
const status = await fetchViaHTTP(appPort, '/api', null, {
method: 'POST',
headers: {
'Content-Type': 'application/json;',
},
body: JSON.stringify([{ title: 'Nextjs' }]),
}).then((res) => res.status)
return status
}
const startServer = async (optEnv = {}, opts) => {
const scriptPath = join(appDir, 'server.js')
context.appPort = appPort = await getPort()
const env = Object.assign(
{},
clone(process.env),
{ PORT: `${appPort}` },
optEnv
)
server = await initNextServerScript(
scriptPath,
/ready on/i,
env,
/ReferenceError: options is not defined/,
opts
)
}
runTests()