-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
70 lines (60 loc) · 1.65 KB
/
index.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
const { createServer } = require("http")
const { parse } = require("url")
const next = require("next")
const axios = require("axios")
const getPort = require("get-port")
const { wrappers } = require("nextjs-middleware-wrappers")
async function getServerFixture(t, options = {}) {
const app = next({
dev: options.dev === undefined ? true : options.dev,
quiet: options.quiet,
dir: options.dir,
})
const handle = app.getRequestHandler()
const port = await getPort()
if (!options.middlewares) options.middlewares = []
let server
await app.prepare().then(() => {
server = createServer(wrappers(...[...options.middlewares, handle]))
server.listen(port)
})
const teardownFn = () => {
if (server) server.close()
}
const shouldTeardown = options.teardown ?? true
if (shouldTeardown) {
t.teardown(teardownFn)
}
const serverURL = `http://127.0.0.1:${port}`
const customAxios = axios.create({
baseURL: serverURL,
})
// Simplify axios errors
customAxios.interceptors.response.use(
(res) => res,
(err) =>
err.request && err.response
? Promise.reject({
url: err.request.path,
status: err.response.status,
statusText: err.response.statusText,
response: err.response.data,
headers: err.response.headers,
})
: Promise.reject(err)
)
return {
port,
serverURL,
axios: customAxios,
close: () => {
if (server) {
server.close()
}
},
teardown: teardownFn,
}
}
module.exports = getServerFixture
module.exports.getServerFixture = getServerFixture
module.exports.default = getServerFixture