forked from kwhitley/itty-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (61 loc) · 1.77 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
71
72
73
/* istanbul ignore file */
const buildRequest = ({
method = 'GET',
path,
url = `https://example.com${path}`,
...other
}) => ({ method, path, url, ...other })
const extract = ({ params, query }) => ({ params, query })
const testRoute = async ({
route,
path,
method = 'get',
returns = true,
log = false,
}, Router) => {
const routes = []
const router = Router({ routes })
const handler = jest.fn(req => req.params)
// register route
router[method](route, handler)
log && console.log({
routes,
route,
path,
})
await router.handle(buildRequest({ method: method.toUpperCase(), path }))
if (!returns) {
expect(handler).not.toHaveBeenCalled()
} else {
expect(handler).toHaveBeenCalled()
if (typeof returns === 'object') {
expect(handler).toHaveReturnedWith(returns)
}
}
}
const runTests = (tests, Router) => {
for (let test of tests) {
let { route, path, returns = true, description } = test
const matchNote = returns
? typeof returns === 'object'
? `returns params ${JSON
.stringify(returns)
.replace('{', '{ ')
.replace('}', ' }')
.replace(/"(\w+)":/g, '$1: ')
.replace(',', ', ')} from`
: 'matches'
: 'does NOT match'
description = description || `route "${route}" ${matchNote} path "${path}"`
it(description, async () => {
await testRoute(test, Router)
})
}
}
const createTestRunner = Router => (...args) => runTests(...args, Router)
module.exports = {
buildRequest,
createTestRunner,
extract,
runTests,
}