-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
98 lines (88 loc) · 3.14 KB
/
index.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
92
93
94
95
96
97
98
import Koa from 'koa'
import Router from '@koa/router'
import axios from 'axios'
import bodyParser from '@koa/bodyparser'
// NOTE: This file is excecuted by the jest environment, which does not share a memory space / module cache with the
// jest test files. This means that any things you want to be able to access from test context
// (like the unmatchedRequests) will need to be bound to the global scope inside the jest-environment and accessed
// through that
let unmatchedRequests = []
export const assertNoUnmatchedRequests = async (
currentClientId,
testNameMap,
) => {
if (unmatchedRequests.length > 0) {
const currentUnmatchedRequests = unmatchedRequests
unmatchedRequests = []
const url = currentUnmatchedRequests[0].config.url
const clientId = url.split('/')[4]
if (url.includes(currentClientId)) {
console.error('Unmatched requests: ' + currentUnmatchedRequests)
throw new Error(
'Unexpected requests received: ' + currentUnmatchedRequests,
)
} else {
const testName = testNameMap[clientId]
console.error(
`Unmatched requests from test case ${testName} ` +
currentUnmatchedRequests,
)
throw new Error(
`Unexpected requests received from test case ${testName} ` +
currentUnmatchedRequests,
)
}
}
}
export function initialize() {
const app = new Koa()
const router = new Router()
router.all('/(.*)', async (ctx) => {
const { headers, request } = ctx
if (process.env.LOG_LEVEL === 'debug') {
console.log(
'Forwarding Request to Nock Server: ',
request.method,
ctx.request.url,
ctx.request.headers,
)
}
try {
let response: any
if (request.method.toLowerCase() === 'get') {
response = await axios.get(
`https://myfakenockurl${ctx.request.url}`,
{
headers,
},
)
} else {
response = await axios[request.method.toLowerCase()](
`https://myfakenockurl${ctx.request.url}`,
request.body,
{
headers,
},
)
}
ctx.body = response.data
ctx.status = response.status
for (const header in response.headers) {
ctx.set(header, response.headers[header])
}
} catch (error) {
if (error.response) {
ctx.body = error.response.data
ctx.status = error.response.status
} else {
console.log(
'Error Forwarding Request to Nock Server: ',
error.message,
)
unmatchedRequests.push(error)
}
}
})
app.use(bodyParser()).use(router.routes()).use(router.allowedMethods())
return app.listen(0)
}