-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathe2e.ts
80 lines (65 loc) · 1.76 KB
/
e2e.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
import { create } from 'axios'
import { type AxiosTestInstance, patchInstance } from 'axios-test-instance'
import { json } from 'body-parser'
import * as express from 'express'
// ——— Shared types ———
interface Credentials {
/**
* The password the user entered.
*/
password: string
/**
* The username the user entered.
*/
username: string
}
interface TokenResponse {
/**
* An OAuth2 access token.
*/
access_token: string
}
// ——— Backend ———
const users: Credentials[] = [
{
password: 'I love krabby patties!',
username: 'spongebob'
}
]
const backend = express()
backend.use(json())
backend.post<never, TokenResponse, Credentials>('/api/token', (req, res) => {
const { password, username } = req.body
const user = users.find((u) => u.username === username && u.password === password)
if (user) {
res.json({ access_token: 'super.secret.token' })
} else {
res.status(401)
}
})
// ——— Frontend ———
const request = create({ baseURL: '/api' })
/**
* Authorize the client side default axios instance.
*
* @param credentials The credentials to login with.
*/
async function login(credentials: Credentials): Promise<void> {
const { data } = await request.post<TokenResponse>('/token', credentials)
request.defaults.headers.common.Authorization = `Bearer ${data.access_token}`
}
// ——— Test ———
let instance: AxiosTestInstance
beforeAll(async () => {
instance = await patchInstance(request, backend)
})
afterAll(async () => {
await instance.close()
})
it('should be possible to login', async () => {
await login({
password: 'I love krabby patties!',
username: 'spongebob'
})
expect(request.defaults.headers.common.Authorization).toBe('Bearer super.secret.token')
})