This repository was archived by the owner on Sep 9, 2022. It is now read-only.
forked from github/docs
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathe2etest.js
More file actions
92 lines (86 loc) · 2.5 KB
/
Copy pathe2etest.js
File metadata and controls
92 lines (86 loc) · 2.5 KB
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
import cheerio from 'cheerio'
import got from 'got'
import { omitBy, isUndefined } from 'lodash-es'
export async function get(
route,
opts = {
method: 'get',
body: undefined,
followRedirects: false,
followAllRedirects: false,
headers: {},
}
) {
const method = opts.method || 'get'
const fn = got[method]
if (!fn || typeof fn !== 'function') throw new Error(`No method function for '${method}'`)
const absURL = `http://localhost:4000${route}`
const xopts = omitBy(
{
body: opts.body,
headers: opts.headers,
retry: { limit: 0 },
throwHttpErrors: false,
followRedirect: opts.followAllRedirects || opts.followRedirects,
},
isUndefined
)
const res = await fn(absURL, xopts)
// follow all redirects, or just follow one
if (opts.followAllRedirects && [301, 302].includes(res.status)) {
// res = await get(res.headers.location, opts)
throw new Error('A')
} else if (opts.followRedirects && [301, 302].includes(res.status)) {
// res = await get(res.headers.location)
throw new Error('B')
}
const text = res.body
const status = res.statusCode
const headers = res.headers
return {
text,
status,
statusCode: status, // Legacy
headers,
header: headers, // Legacy
url: res.url,
}
}
export async function head(route, opts = { followRedirects: false }) {
const res = await get(route, { method: 'head', followRedirects: opts.followRedirects })
return res
}
export function post(route, opts) {
return get(route, Object.assign({}, opts, { method: 'post' }))
}
export async function getDOM(
route,
{ headers, allow500s, allow404 } = {
headers: undefined,
allow500s: false,
allow404: false,
}
) {
const res = await get(route, { followRedirects: true, headers })
if (!allow500s && res.status >= 500) {
throw new Error(`Server error (${res.status}) on ${route}`)
}
if (!allow404 && res.status === 404) {
throw new Error(`Page not found on ${route}`)
}
const $ = cheerio.load(res.text || '', { xmlMode: true })
$.res = Object.assign({}, res)
return $
}
// For use with the ?json query param
// e.g. await getJSON('/en?json=breadcrumbs')
export async function getJSON(route, opts) {
const res = await get(route, { ...opts, followRedirects: true })
if (res.status >= 500) {
throw new Error(`Server error (${res.status}) on ${route}`)
}
if (res.status >= 400) {
console.warn(`${res.status} on ${route} and the response might not be JSON`)
}
return JSON.parse(res.text)
}