-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.test.js
More file actions
103 lines (77 loc) · 2.32 KB
/
auth.test.js
File metadata and controls
103 lines (77 loc) · 2.32 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
93
94
95
96
97
98
99
100
101
102
103
const request = require('supertest')
const {expect} = require('chai')
const db = require('APP/db')
const User = require('APP/db/models/user')
const app = require('./start')
const alice = {
username: 'alice@secrets.org',
password: '12345'
}
describe('/api/auth', () => {
before('Await database sync', () => db.didSync)
afterEach('Clear the tables', () => db.truncate({ cascade: true }))
beforeEach('create a user', () =>
User.create({
email: alice.username,
password: alice.password
})
)
describe('POST /login/local (username, password)', () => {
it('succeeds with a valid username and password', () =>
request(app)
.post('/api/auth/login/local')
.send(alice)
.expect(302)
.expect('Set-Cookie', /session=.*/)
.expect('Location', '/')
)
it('fails with an invalid username and password', () =>
request(app)
.post('/api/auth/login/local')
.send({username: alice.username, password: 'wrong'})
.expect(401)
)
})
describe('GET /whoami', () => {
describe('when not logged in', () => {
it('responds with an empty object', () =>
request(app).get('/api/auth/whoami')
.expect(200)
.then(res => expect(res.body).to.eql({}))
)
})
describe('when logged in', () => {
// supertest agents persist cookies
const agent = request.agent(app)
beforeEach('log in', () => agent
.post('/api/auth/login/local')
.send(alice))
it('responds with the currently logged in user', () =>
agent.get('/api/auth/whoami')
.set('Accept', 'application/json')
.expect(200)
.then(res => expect(res.body).to.contain({
email: alice.username
}))
)
})
})
describe('POST /logout', () => {
describe('when logged in', () => {
const agent = request.agent(app)
beforeEach('log in', () => agent
.post('/api/auth/login/local')
.send(alice))
it('logs you out and redirects to whoami', () => agent
.post('/api/auth/logout')
.expect(302)
.expect('Location', '/api/auth/whoami')
.then(() =>
agent.get('/api/auth/whoami')
.expect(200)
.then(rsp => expect(rsp.body).eql({}))
)
)
})
})
})