Upload 4.23

This commit is contained in:
Andrew Trieu
2023-06-10 15:11:13 +03:00
parent 4b88f3958f
commit a9b6ade2f4
18 changed files with 740 additions and 39 deletions

View File

@@ -5,6 +5,8 @@ const app = require('../app')
const api = supertest(app)
const Blog = require('../models/blog')
const bcrypt = require('bcrypt')
const User = require('../models/user')
const helper = require('./test_helper')
beforeEach(async () => {
@@ -117,6 +119,27 @@ describe('updating blog', () => {
const contents = blogsAtEnd.map((r) => r.title)
expect(contents).toContain('Updated blog')
})
test('creation fails with proper statuscode and message if username already taken', async () => {
const usersAtStart = await helper.usersInDb()
const newUser = {
username: 'root',
name: 'Superuser',
password: 'salainen',
}
const result = await api
.post('/api/users')
.send(newUser)
.expect(400)
.expect('Content-Type', /application\/json/)
expect(result.body.error).toContain('expected `username` to be unique')
const usersAtEnd = await helper.usersInDb()
expect(usersAtEnd).toEqual(usersAtStart)
})
})
describe('blog id check', () => {
@@ -126,6 +149,61 @@ describe('blog id check', () => {
})
})
describe('when there is initially one user in db', () => {
beforeEach(async () => {
await User.deleteMany({})
const passwordHash = await bcrypt.hash('sekret', 10)
const user = new User({ username: 'root', passwordHash })
await user.save()
})
test('creation succeeds with a fresh username', async () => {
const usersAtStart = await helper.usersInDb()
const newUser = {
username: 'mluukkai',
name: 'Matti Luukkainen',
password: 'salainen',
}
await api
.post('/api/users')
.send(newUser)
.expect(201)
.expect('Content-Type', /application\/json/)
const usersAtEnd = await helper.usersInDb()
expect(usersAtEnd).toHaveLength(usersAtStart.length + 1)
const usernames = usersAtEnd.map(u => u.username)
expect(usernames).toContain(newUser.username)
})
})
describe('user validation', () => {
test('username must be at least 3 characters long', async () => {
const newUser = {
username: 'ml',
name: 'Matti Luukkainen',
password: 'salainen',
}
await api.post('/api/users').send(newUser).expect(400)
})
test('password must be at least 3 characters long', async () => {
const newUser = {
username: 'mluukkai',
name: 'Matti Luukkainen',
password: 'sa',
}
await api.post('/api/users').send(newUser).expect(400)
})
})
afterAll(async () => {
await mongoose.connection.close()
})

View File

@@ -1,4 +1,5 @@
const Blog = require('../models/blog')
const User = require('../models/user')
const initialBlogs = [
{
@@ -40,6 +41,11 @@ const blogsInDb = async () => {
return blogs.map(blog => blog.toJSON())
}
const usersInDb = async () => {
const users = await User.find({})
return users.map(user => user.toJSON())
}
module.exports = {
initialBlogs, nonExistingId, blogsInDb
initialBlogs, nonExistingId, blogsInDb, usersInDb
}