Skip to content

Commit 070a4b5

Browse files
committed
add test to user update
1 parent 2989241 commit 070a4b5

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

controllers/loginController.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ loginRouter.post('/', async (request, response) => {
2828

2929
const token = jwt.sign(userForToken, process.env.SECRET)
3030

31-
response.status(200).send({ token, username: user.username, name: user.name })
31+
response
32+
.status(200)
33+
.send({ token, id: user.id, username: user.username, name: user.name })
3234
})
3335

3436
module.exports = loginRouter

tests/user.test.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,26 @@ const app = require('../app')
44
const api = supertest(app)
55
const bcrypt = require('bcrypt')
66
const User = require('../models/user')
7+
const { tokenExtractor } = require('../utils/middleware')
78

89
describe('when there is initially one user in db', () => {
10+
let token // Token of authenticated user
11+
let userId // ID of authenticated user
12+
913
beforeEach(async () => {
1014
await User.deleteMany({})
1115

1216
const passwordHash = await bcrypt.hash('sekret', 10)
1317
const user = new User({ username: 'root', passwordHash })
1418

1519
await user.save()
20+
21+
const response = await api
22+
.post('/api/login')
23+
.send({ username: 'root', password: 'sekret' })
24+
25+
token = response.body.token
26+
userId = response.body.id
1627
})
1728

1829
test('creation succeeds with a fresh username', async () => {
@@ -140,4 +151,29 @@ describe('when there is initially one user in db', () => {
140151
'`password` is shorter than the minimum allowed length (3)'
141152
)
142153
})
154+
155+
test('should update user data', async () => {
156+
// Make a PUT request to update a user's data
157+
const response = await api
158+
.put(`/api/users/${userId}`)
159+
.set('Authorization', `bearer ${token}`) // Set the Authorization header
160+
.send({
161+
username: 'root',
162+
name: 'newname',
163+
password: 'sekret',
164+
email: 'new@email.com',
165+
})
166+
167+
console.log(`User: /api/users/${userId}`)
168+
console.log(`Token: ${token}`)
169+
// Verify that the response is successful and has the new username
170+
expect(response.status).toBe(200)
171+
expect(response.body.name).toBe('newname')
172+
})
173+
174+
// Other user-related tests can go here
175+
176+
afterAll(() => {
177+
// Perform any necessary cleanup after the tests, such as closing database connections if needed
178+
})
143179
})

0 commit comments

Comments
 (0)