Skip to content

Commit

Permalink
add test to user update
Browse files Browse the repository at this point in the history
  • Loading branch information
patchamama committed Sep 13, 2023
1 parent 2989241 commit 070a4b5
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
4 changes: 3 additions & 1 deletion controllers/loginController.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ loginRouter.post('/', async (request, response) => {

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

response.status(200).send({ token, username: user.username, name: user.name })
response
.status(200)
.send({ token, id: user.id, username: user.username, name: user.name })
})

module.exports = loginRouter
36 changes: 36 additions & 0 deletions tests/user.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,26 @@ const app = require('../app')
const api = supertest(app)
const bcrypt = require('bcrypt')
const User = require('../models/user')
const { tokenExtractor } = require('../utils/middleware')

describe('when there is initially one user in db', () => {
let token // Token of authenticated user
let userId // ID of authenticated user

beforeEach(async () => {
await User.deleteMany({})

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

await user.save()

const response = await api
.post('/api/login')
.send({ username: 'root', password: 'sekret' })

token = response.body.token
userId = response.body.id
})

test('creation succeeds with a fresh username', async () => {
Expand Down Expand Up @@ -140,4 +151,29 @@ describe('when there is initially one user in db', () => {
'`password` is shorter than the minimum allowed length (3)'
)
})

test('should update user data', async () => {
// Make a PUT request to update a user's data
const response = await api
.put(`/api/users/${userId}`)
.set('Authorization', `bearer ${token}`) // Set the Authorization header
.send({
username: 'root',
name: 'newname',
password: 'sekret',
email: 'new@email.com',
})

console.log(`User: /api/users/${userId}`)
console.log(`Token: ${token}`)
// Verify that the response is successful and has the new username
expect(response.status).toBe(200)
expect(response.body.name).toBe('newname')
})

// Other user-related tests can go here

afterAll(() => {
// Perform any necessary cleanup after the tests, such as closing database connections if needed
})
})

0 comments on commit 070a4b5

Please sign in to comment.