Fixed tests

This commit is contained in:
Hackntosh 2023-07-20 08:15:29 -03:00
parent 08612929ea
commit b6be9d6755
47 changed files with 189 additions and 324 deletions

View file

@ -26,6 +26,8 @@ COPY --from=builder /app/dist ./dist/
RUN npm ci RUN npm ci
RUN npm run prisma:deploy
EXPOSE 8080 EXPOSE 8080
CMD ["npm", "run", "prod:start"] CMD ["npm", "run", "prod:start"]

View file

@ -2,6 +2,7 @@
module.exports = { module.exports = {
preset: 'ts-jest', preset: 'ts-jest',
testEnvironment: 'node', testEnvironment: 'node',
setupFilesAfterEnv: ['<rootDir>/setupTest.ts'],
transform: { transform: {
'^.+\\.(t|j)sx?$': '@swc/jest' '^.+\\.(t|j)sx?$': '@swc/jest'
} }

7
setupTest.ts Normal file
View file

@ -0,0 +1,7 @@
import prisma from './src/clients/prisma-client'
import redis from './src/clients/redis-client'
afterAll(async () => {
redis.disconnect()
await prisma.$disconnect()
})

View file

@ -1,3 +1,4 @@
/* eslint-disable */
import * as express from 'express' import * as express from 'express'
import jwtPayload from '../interfaces/jwt' import jwtPayload from '../interfaces/jwt'

View file

@ -7,11 +7,8 @@ import limiter from './middlewares/rate-limit'
const app = express() const app = express()
// TODO: Disable image resize when it's a post attachment // TODO: find a way to declare global variables for better refactor on test
// TODO: Add user-upload-picture tests // TODO: must pass userMock as a global
// TODO: Apply http-errors lib on the controllers
// TODO: Automatically apply the newest migration when starting up the docker
// TODO: Refactor some parts of the code
app.use(express.json()) app.use(express.json())
app.use(express.urlencoded({ extended: true })) app.use(express.urlencoded({ extended: true }))

View file

@ -0,0 +1,9 @@
import RedisClient from 'ioredis'
const redisPassword = process.env.REDIS_PASSWORD ?? ''
const redisHost = process.env.REDIS_HOST ?? ''
const redisPort = process.env.REDIS_PORT ?? ''
const redis = new RedisClient(`redis://:${redisPassword}@${redisHost}:${redisPort}/0`)
export default redis

View file

@ -1,7 +1,7 @@
import multer from 'multer' import multer from 'multer'
import { Request } from 'express' import { Request } from 'express'
import path from 'path' import path from 'path'
import s3 from './clients/s3-client' import s3 from '../clients/s3-client'
import multerS3 from 'multer-s3' import multerS3 from 'multer-s3'
const tempFolder = path.resolve(__dirname, '..', '..', 'temp', 'uploads') const tempFolder = path.resolve(__dirname, '..', '..', 'temp', 'uploads')

View file

@ -1,5 +1,6 @@
import { post } from '../../services/index' import { post } from '../../services/index'
import { Request, Response } from 'express' import type { Request, Response } from 'express'
import { badRequest } from '../../lib/http-errors'
async function postCreateController (req: Request, res: Response): Promise<void> { async function postCreateController (req: Request, res: Response): Promise<void> {
const { content } = req.body const { content } = req.body
@ -8,10 +9,7 @@ async function postCreateController (req: Request, res: Response): Promise<void>
const result = await post.create(content, id) const result = await post.create(content, id)
if (result instanceof Error) { if (result instanceof Error) {
res.status(400).json({ return badRequest(res, result.message)
error: result.message
})
return
} }
res.json(result) res.json(result)

View file

@ -1,5 +1,6 @@
import { post } from '../../services/index' import { post } from '../../services/index'
import { Request, Response } from 'express' import type { Request, Response } from 'express'
import { badRequest } from '../../lib/http-errors'
async function postDeleteController (req: Request, res: Response): Promise<void> { async function postDeleteController (req: Request, res: Response): Promise<void> {
const userId = req.user?.id ?? '' const userId = req.user?.id ?? ''
@ -8,10 +9,7 @@ async function postDeleteController (req: Request, res: Response): Promise<void>
const result = await post.delete(postId, userId) const result = await post.delete(postId, userId)
if (result instanceof Error) { if (result instanceof Error) {
res.status(400).json({ return badRequest(res, result.message)
error: result.message
})
return
} }
res.json(result) res.json(result)

View file

@ -1,23 +1,18 @@
import { post } from '../../services/index' import { post } from '../../services/index'
import { Request, Response } from 'express' import type { Request, Response } from 'express'
import { badRequest } from '../../lib/http-errors'
async function postInfoController (req: Request, res: Response): Promise<void> { async function postInfoController (req: Request, res: Response): Promise<void> {
const id = req.query.id as string const id = req.query.id as string
if (id === undefined) { if (id === undefined) {
res.status(400).json({ return badRequest(res, 'Missing post id')
error: 'Missing username'
})
return
} }
const result = await post.info(id) const result = await post.info(id)
if (result instanceof Error) { if (result instanceof Error) {
res.status(400).json({ return badRequest(res, result.message)
error: result.message
})
return
} }
res.json(result) res.json(result)

View file

@ -1,5 +1,6 @@
import { post } from '../../services/index' import { post } from '../../services/index'
import { Request, Response } from 'express' import type { Request, Response } from 'express'
import { badRequest } from '../../lib/http-errors'
async function postUpdateController (req: Request, res: Response): Promise<void> { async function postUpdateController (req: Request, res: Response): Promise<void> {
const { postId, content } = req.body const { postId, content } = req.body
@ -8,10 +9,7 @@ async function postUpdateController (req: Request, res: Response): Promise<void>
const result = await post.update(postId, content, userId) const result = await post.update(postId, content, userId)
if (result instanceof Error) { if (result instanceof Error) {
res.status(400).json({ return badRequest(res, result.message)
error: result.message
})
return
} }
res.json(result) res.json(result)

View file

@ -1,5 +1,6 @@
import { user } from '../../services/index' import { user } from '../../services/index'
import type { Request, Response } from 'express' import type { Request, Response } from 'express'
import { badRequest } from '../../lib/http-errors'
async function userAuthController (req: Request, res: Response): Promise<void> { async function userAuthController (req: Request, res: Response): Promise<void> {
const { email, password } = req.body const { email, password } = req.body
@ -7,10 +8,7 @@ async function userAuthController (req: Request, res: Response): Promise<void> {
const result = await user.auth(email, password) const result = await user.auth(email, password)
if (result instanceof Error) { if (result instanceof Error) {
res.status(400).json({ return badRequest(res, result.message)
error: result.message
})
return
} }
res.json(result) res.json(result)

View file

@ -1,15 +1,13 @@
import { user } from '../../services' import { user } from '../../services'
import { Request, Response } from 'express' import type { Request, Response } from 'express'
import { badRequest } from '../../lib/http-errors'
async function userDeleteController (req: Request, res: Response): Promise<void> { async function userDeleteController (req: Request, res: Response): Promise<void> {
const userId = req.user?.id ?? '' const userId = req.user?.id ?? ''
const result = await user.delete(userId) const result = await user.delete(userId)
if (result instanceof Error) { if (result instanceof Error) {
res.status(400).json({ return badRequest(res, result.message)
error: result.message
})
return
} }
res.json(result) res.json(result)

View file

@ -1,23 +1,18 @@
import { user } from '../../services' import { user } from '../../services'
import type { Request, Response } from 'express' import type { Request, Response } from 'express'
import { badRequest } from '../../lib/http-errors'
async function userInfoController (req: Request, res: Response): Promise<void> { async function userInfoController (req: Request, res: Response): Promise<void> {
const username = req.query.u as string const username = req.query.u as string
if (username === undefined) { if (username === undefined) {
res.status(400).json({ return badRequest(res, 'Missing username')
error: 'Missing username'
})
return
} }
const result = await user.info(username.toLowerCase()) const result = await user.info(username.toLowerCase())
if (result instanceof Error) { if (result instanceof Error) {
res.status(400).json({ return badRequest(res, result.message)
error: result.message
})
return
} }
res.json(result) res.json(result)

View file

@ -1,5 +1,6 @@
import { user } from '../../services' import { user } from '../../services'
import type { Request, Response } from 'express' import type { Request, Response } from 'express'
import { badRequest } from '../../lib/http-errors'
async function userSignupController (req: Request, res: Response): Promise<void> { async function userSignupController (req: Request, res: Response): Promise<void> {
const { username, email, password } = req.body const { username, email, password } = req.body
@ -7,10 +8,7 @@ async function userSignupController (req: Request, res: Response): Promise<void>
const result = await user.signup(username, email, password) const result = await user.signup(username, email, password)
if (result instanceof Error) { if (result instanceof Error) {
res.status(400).json({ return badRequest(res, result.message)
error: result.message
})
return
} }
res.json(result) res.json(result)

View file

@ -1,5 +1,6 @@
import { user } from '../../services' import { user } from '../../services'
import { Request, Response } from 'express' import type { Request, Response } from 'express'
import { badRequest } from '../../lib/http-errors'
async function userUpdateController (req: Request, res: Response): Promise<void> { async function userUpdateController (req: Request, res: Response): Promise<void> {
const { email, displayName, username } = req.body const { email, displayName, username } = req.body
@ -8,10 +9,7 @@ async function userUpdateController (req: Request, res: Response): Promise<void>
const result = await user.update({ id, email, displayName, username }) const result = await user.update({ id, email, displayName, username })
if (result instanceof Error) { if (result instanceof Error) {
res.status(400).json({ return badRequest(res, result.message)
error: result.message
})
return
} }
res.json(result) res.json(result)

View file

@ -1,5 +1,6 @@
import userUploadPictureService from '../../services/users/user-upload-picture' /* eslint-disable @typescript-eslint/restrict-template-expressions */
import { Request, Response } from 'express' import { user } from '../../services/index'
import type { Request, Response } from 'express'
import { badRequest } from '../../lib/http-errors' import { badRequest } from '../../lib/http-errors'
let url let url
@ -12,7 +13,6 @@ async function userUploadPictureController (req: Request, res: Response): Promis
const userId = req.user?.id ?? '' const userId = req.user?.id ?? ''
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
/* eslint-disable */
// @ts-expect-error property `key` doesn't exists in @types/express // @ts-expect-error property `key` doesn't exists in @types/express
url = `http://${process.env.AWS_BUCKET ?? ''}.s3.localhost.localstack.cloud:4566/${req.file.key}` url = `http://${process.env.AWS_BUCKET ?? ''}.s3.localhost.localstack.cloud:4566/${req.file.key}`
} else { } else {
@ -20,7 +20,7 @@ async function userUploadPictureController (req: Request, res: Response): Promis
url = req.file.location url = req.file.location
} }
const result = await userUploadPictureService(userId, url) const result = await user.uploadPicture(userId, url)
if (result instanceof Error) { if (result instanceof Error) {
return badRequest(res, result.message) return badRequest(res, result.message)

View file

@ -1,5 +1,5 @@
import sharp from 'sharp' import sharp from 'sharp'
import s3 from '../config/clients/s3-client' import s3 from '../clients/s3-client'
import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3' import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'
export default async function compressImage (imageName: string): Promise<Error | Object > { export default async function compressImage (imageName: string): Promise<Error | Object > {
@ -12,8 +12,7 @@ export default async function compressImage (imageName: string): Promise<Error |
const imageBuffer = await Body?.transformToByteArray() const imageBuffer = await Body?.transformToByteArray()
const compressedImageBuffer = await sharp(imageBuffer) const compressedImageBuffer = await sharp(imageBuffer)
.resize(200, 200) .jpeg({ quality: 65 })
.jpeg({ quality: 80 })
.toBuffer() .toBuffer()
// Send file back // Send file back

View file

@ -1,14 +1,12 @@
import { verify } from 'jsonwebtoken' import { verify } from 'jsonwebtoken'
import prisma from '../db' import prisma from '../clients/prisma-client'
import { Response, Request, NextFunction } from 'express' import type { Response, Request, NextFunction } from 'express'
import jwtPayload from '../interfaces/jwt' import jwtPayload from '../interfaces/jwt'
import { unauthorized } from '../lib/http-errors'
async function ensureAuthenticated (req: Request, res: Response, next: NextFunction): Promise<void> { async function ensureAuthenticated (req: Request, res: Response, next: NextFunction): Promise<void> {
if (req.headers.authorization === undefined || req.headers.authorization.length === 0) { if (req.headers.authorization === undefined || req.headers.authorization.length === 0) {
res.status(401).json({ return unauthorized(res, 'Missing token')
error: 'Missing token'
})
return
} }
const token = req.headers.authorization.split(' ')[1] const token = req.headers.authorization.split(' ')[1]
@ -25,10 +23,7 @@ async function ensureAuthenticated (req: Request, res: Response, next: NextFunct
}) })
if (decoded == null) { if (decoded == null) {
res.status(401).json({ return unauthorized(res, 'Invalid token')
error: 'Invalid token'
})
return
} }
const user = await prisma.user.findFirst({ const user = await prisma.user.findFirst({
@ -38,19 +33,14 @@ async function ensureAuthenticated (req: Request, res: Response, next: NextFunct
}) })
if (user == null) { if (user == null) {
res.status(401).json({ return unauthorized(res, 'User does not exists')
error: 'Invalid user'
})
return
} }
req.user = decoded req.user = decoded
return next() return next()
} catch (error) { } catch (error) {
res.status(401).json({ unauthorized(res, `JWT Error: ${(error as Error).message}`)
error: `JWT Error: ${(error as Error).message}`
})
} }
} }

View file

@ -1,12 +1,6 @@
import rateLimit from 'express-rate-limit' import rateLimit from 'express-rate-limit'
import RedisStore from 'rate-limit-redis' import RedisStore from 'rate-limit-redis'
import RedisClient from 'ioredis' import redis from '../clients/redis-client'
const redisPassword = process.env.REDIS_PASSWORD ?? ''
const redisHost = process.env.REDIS_HOST ?? ''
const redisPort = process.env.REDIS_PORT ?? ''
const client = new RedisClient(`redis://:${redisPassword}@${redisHost}:${redisPort}/0`)
let maxConnections let maxConnections
@ -26,7 +20,7 @@ const limiter = rateLimit({
// Store configuration // Store configuration
store: new RedisStore({ store: new RedisStore({
// @ts-expect-error - `call` function is not present in @types/ioredis // @ts-expect-error - `call` function is not present in @types/ioredis
sendCommand: async (...args: string[]) => await client.call(...args) sendCommand: async (...args: string[]) => await redis.call(...args)
}) })
}) })

View file

@ -1,34 +1,25 @@
/* eslint-disable @typescript-eslint/no-misused-promises */ /* eslint-disable @typescript-eslint/no-misused-promises */
/* eslint-disable @typescript-eslint/explicit-function-return-type */ /* eslint-disable @typescript-eslint/explicit-function-return-type */
import { Response, Request, NextFunction } from 'express' import type { Response, Request, NextFunction } from 'express'
import multer from 'multer' import multer from 'multer'
import multerConfig from '../config/multer' import multerConfig from '../config/multer'
import compressImage from '../lib/compress-image' import compressImage from '../lib/compress-image'
import { badRequest } from '../lib/http-errors'
function uploadImage (req: Request, res: Response, next: NextFunction) { function uploadImage (req: Request, res: Response, next: NextFunction) {
const upload = multer(multerConfig).single('image') const upload = multer(multerConfig).single('image')
upload(req, res, async (cb: multer.MulterError | Error | any) => { upload(req, res, async (cb: multer.MulterError | Error | any) => {
if (req.user == null) { if (req.user == null) {
return res.status(400).json({ return badRequest(res, 'You must be logged in to upload a profile picture')
error: 'You must be logged in to upload a profile picture'
})
} }
if (cb instanceof multer.MulterError || cb instanceof Error) { if (cb instanceof multer.MulterError || cb instanceof Error) {
return res.status(400).json({ return badRequest(res, cb.message)
error: cb.message
})
} }
// @ts-expect-error property `key` does not exists in types // @ts-expect-error property `key` does not exists in types
const compressed = await compressImage(req.file?.key) await compressImage(req.file?.key)
if (compressed instanceof Error) {
return res.status(500).json({
error: compressed.message
})
}
next() next()
}) })

View file

@ -3,6 +3,7 @@ import userDeleteService from './users/user-delete'
import userInfoService from './users/user-info' import userInfoService from './users/user-info'
import userSignupService from './users/user-signup' import userSignupService from './users/user-signup'
import userUpdateService from './users/user-update' import userUpdateService from './users/user-update'
import userUploadPictureService from './users/user-upload-picture'
import postCreateService from './posts/post-create' import postCreateService from './posts/post-create'
import postDeleteService from './posts/post-delete' import postDeleteService from './posts/post-delete'
@ -15,7 +16,8 @@ const user = {
delete: userDeleteService, delete: userDeleteService,
info: userInfoService, info: userInfoService,
signup: userSignupService, signup: userSignupService,
update: userUpdateService update: userUpdateService,
uploadPicture: userUploadPictureService
} }
// Post services // Post services

View file

@ -1,4 +1,4 @@
import prisma from '../../db' import prisma from '../../clients/prisma-client'
async function postCreateService (content: string, authorId: string): Promise<Object | Error> { async function postCreateService (content: string, authorId: string): Promise<Object | Error> {
const user = await prisma.user.findFirst({ where: { id: authorId } }) const user = await prisma.user.findFirst({ where: { id: authorId } })

View file

@ -1,4 +1,4 @@
import prisma from '../../db' import prisma from '../../clients/prisma-client'
async function postDeleteService (postId: string, userId: string): Promise<Object | Error> { async function postDeleteService (postId: string, userId: string): Promise<Object | Error> {
const post = await prisma.post.findFirst({ where: { id: postId } }) const post = await prisma.post.findFirst({ where: { id: postId } })

View file

@ -1,4 +1,4 @@
import prisma from '../../db' import prisma from '../../clients/prisma-client'
async function postInfoService (id: string): Promise<Object | Error> { async function postInfoService (id: string): Promise<Object | Error> {
const post = await prisma.post.findFirst({ const post = await prisma.post.findFirst({

View file

@ -1,4 +1,4 @@
import prisma from '../../db' import prisma from '../../clients/prisma-client'
async function postUpdateService (postId: string, content: string, userId: string): Promise<Object | Error> { async function postUpdateService (postId: string, content: string, userId: string): Promise<Object | Error> {
const post = await prisma.post.findFirst({ where: { id: postId } }) const post = await prisma.post.findFirst({ where: { id: postId } })

View file

@ -1,6 +1,6 @@
import * as bcrypt from 'bcrypt' import * as bcrypt from 'bcrypt'
import jsonwebtoken from 'jsonwebtoken' import jsonwebtoken from 'jsonwebtoken'
import prisma from '../../db' import prisma from '../../clients/prisma-client'
async function userAuthService (email: string, password: string): Promise<Object | Error> { async function userAuthService (email: string, password: string): Promise<Object | Error> {
const user = await prisma.user.findFirst({ const user = await prisma.user.findFirst({

View file

@ -1,4 +1,4 @@
import prisma from '../../db' import prisma from '../../clients/prisma-client'
async function userDeleteService (userId: string): Promise<Object | Error> { async function userDeleteService (userId: string): Promise<Object | Error> {
const user = await prisma.user.findFirst({ where: { id: userId } }) const user = await prisma.user.findFirst({ where: { id: userId } })

View file

@ -1,4 +1,4 @@
import prisma from '../../db' import prisma from '../../clients/prisma-client'
async function userInfoService (username: string): Promise<Object> { async function userInfoService (username: string): Promise<Object> {
const user = await prisma.user.findFirst({ const user = await prisma.user.findFirst({

View file

@ -1,8 +1,8 @@
import * as bcrypt from 'bcrypt' import * as bcrypt from 'bcrypt'
import validator from 'validator' import validator from 'validator'
import prisma from '../../db' import prisma from '../../clients/prisma-client'
const passwordRegex = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,}$/ const passwordRegex = /^(?=.*[0-9])(?=.*[!@#$%^&*_])[a-zA-Z0-9!@#$%^&*_]{8,}$/
const usernameRegex = /^[a-zA-Z0-9_.]{5,15}$/ const usernameRegex = /^[a-zA-Z0-9_.]{5,15}$/
async function userSignupService (username: string, email: string, password: string): Promise<Object | Error> { async function userSignupService (username: string, email: string, password: string): Promise<Object | Error> {
@ -11,7 +11,7 @@ async function userSignupService (username: string, email: string, password: str
} }
if (!passwordRegex.test(password)) { if (!passwordRegex.test(password)) {
return new Error('Password must have 8 characters, one number and one special character.') return new Error('Password must have at least 8 characters, one number and one special character.')
} }
if (password.trim().length < 8) { if (password.trim().length < 8) {

View file

@ -1,5 +1,5 @@
import userPayload from '../../interfaces/user' import userPayload from '../../interfaces/user'
import prisma from '../../db' import prisma from '../../clients/prisma-client'
async function userUpdateService ({ id, email, displayName, username }: userPayload): Promise<Object | Error> { async function userUpdateService ({ id, email, displayName, username }: userPayload): Promise<Object | Error> {
const user = await prisma.user.findFirst({ where: { id } }) const user = await prisma.user.findFirst({ where: { id } })

View file

@ -1,4 +1,4 @@
import prisma from '../../db' import prisma from '../../clients/prisma-client'
async function userUploadPictureService (authorId: string, url: string): Promise<Object | Error> { async function userUploadPictureService (authorId: string, url: string): Promise<Object | Error> {
const user = await prisma.user.findFirst({ where: { id: authorId } }) const user = await prisma.user.findFirst({ where: { id: authorId } })

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

View file

@ -1,39 +1,24 @@
import prisma from '../../db'
import app from '../../app' import app from '../../app'
import request from 'supertest' import request from 'supertest'
import signUpNewUser from '../utils/create-user' import signUpNewUser from '../utils/create-user'
import deleteUser from '../utils/delete-user'
import userPayload from '../../interfaces/user'
let token = ''; let username = '' let user: userPayload
describe('POST /post/create', () => { describe('POST /post/create', () => {
beforeAll(async () => { beforeAll(async () => {
const user = await signUpNewUser() user = await signUpNewUser()
token = user.token ?? ''
username = user.username ?? ''
}) })
afterAll(async () => { afterAll(async () => {
await prisma.post.deleteMany({ await deleteUser(user.username ?? '')
where: {
author: {
username
}
}
})
await prisma.user.deleteMany({
where: {
username
}
})
await prisma.$disconnect()
}) })
it('should respond with 200 status code if the user send the token and the content', async () => { it('should respond with 200 status code if the user send the token and the content', async () => {
const response = await request(app).post('/post/create').send({ const response = await request(app).post('/post/create').send({
content: '4764ba063310b6f8bab31e8348b2188a' content: 'Hello world'
}).set('Authorization', `Bearer ${token}`).expect(200) }).set('Authorization', `Bearer ${user.token ?? ''}`).expect(200)
expect(response.body).toEqual(expect.objectContaining({ expect(response.body).toEqual(expect.objectContaining({
id: expect.any(String), id: expect.any(String),

View file

@ -1,26 +1,18 @@
import prisma from '../../db'
import app from '../../app' import app from '../../app'
import request from 'supertest' import request from 'supertest'
import signUpNewUser from '../utils/create-user' import signUpNewUser from '../utils/create-user'
import deleteUser from '../utils/delete-user'
import userPayload from '../../interfaces/user'
let token = ''; let username = '' let user: userPayload
describe('DELETE /post/delete', () => { describe('DELETE /post/delete', () => {
beforeAll(async () => { beforeAll(async () => {
const user = await signUpNewUser() user = await signUpNewUser()
token = user.token ?? ''
username = user.username ?? ''
}) })
afterAll(async () => { afterAll(async () => {
await prisma.user.deleteMany({ await deleteUser(user.username ?? '')
where: {
username
}
})
await prisma.$disconnect()
}) })
it('should delete the post successfully', async () => { it('should delete the post successfully', async () => {
@ -29,13 +21,13 @@ describe('DELETE /post/delete', () => {
.send({ .send({
content: 'lorem ipsum' content: 'lorem ipsum'
}) })
.set('Authorization', `Bearer ${token}`).expect(200) .set('Authorization', `Bearer ${user.token ?? ''}`).expect(200)
await request(app) await request(app)
.post('/post/delete') .post('/post/delete')
.send({ .send({
postId: response.body.id postId: response.body.id
}) })
.set('Authorization', `Bearer ${token}`).expect(200) .set('Authorization', `Bearer ${user.token ?? ''}`).expect(200)
}) })
}) })

View file

@ -1,37 +1,28 @@
import prisma from '../../db'
import app from '../../app' import app from '../../app'
import request from 'supertest' import request from 'supertest'
import signUpNewUser from '../utils/create-user' import signUpNewUser from '../utils/create-user'
import deleteUser from '../utils/delete-user'
import userPayload from '../../interfaces/user'
let postId = ''; let username = '' let postId: string
let user: userPayload
describe('POST /post/info', () => { describe('POST /post/info', () => {
beforeAll(async () => { beforeAll(async () => {
const user = await signUpNewUser() user = await signUpNewUser()
const token = user.token ?? '' const token = user.token ?? ''
const post = await request(app).post('/post/create').send({ const post = await request(app).post('/post/create').send({
content: 'nothing to see here!' content: 'Hello world'
}).set('Authorization', `Bearer ${token}`).expect(200) }).set('Authorization', `Bearer ${token}`).expect(200)
username = user.username ?? ''
postId = post.body.id postId = post.body.id
}) })
afterAll(async () => { afterAll(async () => {
await prisma.post.deleteMany({ await deleteUser(user.username ?? '')
where: {
id: postId
}
})
await prisma.user.deleteMany({
where: {
username
}
})
await prisma.$disconnect()
}) })
it('should respond with 200 status code and return some info about the post', async () => { it('should respond with 200 status code and return some info about the post', async () => {
@ -47,7 +38,7 @@ describe('POST /post/info', () => {
}) })
it('should respond with 400 status code if the post does not exists', async () => { it('should respond with 400 status code if the post does not exists', async () => {
const response = await request(app).get('/post/info?id=randominfohere').expect(400) const response = await request(app).get('/post/info?id=abc').expect(400)
expect(response.body).toHaveProperty('error') expect(response.body).toHaveProperty('error')
}) })

View file

@ -1,40 +1,24 @@
import prisma from '../../db'
import app from '../../app' import app from '../../app'
import request from 'supertest' import request from 'supertest'
import signUpNewUser from '../utils/create-user' import signUpNewUser from '../utils/create-user'
import deleteUser from '../utils/delete-user'
import userPayload from '../../interfaces/user'
let token = ''; let username = '' let user: userPayload
describe('PUT /post/update', () => { describe('PUT /post/update', () => {
beforeAll(async () => { beforeAll(async () => {
const user = await signUpNewUser() user = await signUpNewUser()
username = user.username ?? ''
token = user.token ?? ''
}) })
afterAll(async () => { afterAll(async () => {
await prisma.post.deleteMany({ await deleteUser(user.username ?? '')
where: {
author: {
username
}
}
})
await prisma.user.deleteMany({
where: {
username
}
})
await prisma.$disconnect()
}) })
it('should create a new post and update the content of it', async () => { it('should create a new post and update the content of it', async () => {
const post = await request(app).post('/post/create').send({ const post = await request(app).post('/post/create').send({
content: 'Lorem' content: 'Lorem'
}).set('Authorization', `Bearer ${token}`).expect(200) }).set('Authorization', `Bearer ${user.token ?? ''}`).expect(200)
expect(post.body).toHaveProperty('id') expect(post.body).toHaveProperty('id')
@ -46,7 +30,7 @@ describe('PUT /post/update', () => {
const response = await request(app) const response = await request(app)
.put('/post/update') .put('/post/update')
.send(fieldsToUpdate) .send(fieldsToUpdate)
.set('Authorization', `Bearer ${token}`).expect(200) .set('Authorization', `Bearer ${user.token ?? ''}`).expect(200)
// Post content should be Lorem Ipsum // Post content should be Lorem Ipsum
if (post.body.content === response.body.content) { if (post.body.content === response.body.content) {

View file

@ -1,50 +1,37 @@
import request from 'supertest' import request from 'supertest'
import prisma from '../../db'
import app from '../../app' import app from '../../app'
import deleteUser from '../utils/delete-user'
import signUpNewUser from '../utils/create-user'
import userPayload from '../../interfaces/user'
let user: userPayload
describe('POST /user/auth', () => { describe('POST /user/auth', () => {
beforeAll(async () => { beforeAll(async () => {
await prisma.user.create({ user = await signUpNewUser()
data: {
username: 'dummmyuser6',
email: 'test@test.com',
password: 'pass'
}
})
}) })
afterAll(async () => { afterAll(async () => {
await prisma.user.deleteMany({ await deleteUser(user.username ?? '')
where: {
username: 'dummmyuser6'
}
})
await prisma.$disconnect()
}) })
it('should respond with a error if the user does not exists', async () => { it('should respond with a error if the user does not exists', async () => {
const response = await request(app) const response = await request(app).post('/user/auth').send({ email: 'mm@mm.com', password: 'aa' }).expect(400)
.post('/user/auth')
.send({
email: 'mm@mm.com',
password: 'aa'
}).expect(400)
expect(response.body).toHaveProperty('error') expect(response.body).toHaveProperty('error')
expect(response.body.error).toBe('User does not exists') expect(response.body.error).toBe('User does not exists')
}) })
it('should respond with a error if receive an invalid email or password', async () => { it('should respond with a error if receive an invalid email or password', async () => {
const response = await request(app) const response = await request(app).post('/user/auth').send({ email: user.email, password: 'fake_pass' }).expect(400)
.post('/user/auth').send({
email: 'test@test.com',
password: 'haha'
}).expect(400)
expect(response.body).toHaveProperty('error') expect(response.body).toHaveProperty('error')
expect(response.body.error).toBe('Invalid email or password') expect(response.body.error).toBe('Invalid email or password')
}) })
it('should respond with a error if receive an empty body', async () => { it('should respond with a error if receive an empty body', async () => {
const response = await request(app).post('/user/auth').send({}).expect(400) const response = await request(app).post('/user/auth').send({}).expect(400)
expect(response.body).toHaveProperty('error') expect(response.body).toHaveProperty('error')
expect(response.body.error).toBe('Missing fields') expect(response.body.error).toBe('Missing fields')
}) })

View file

@ -1,23 +1,18 @@
import prisma from '../../db'
import app from '../../app' import app from '../../app'
import request from 'supertest' import request from 'supertest'
import signUpNewUser from '../utils/create-user' import signUpNewUser from '../utils/create-user'
import userPayload from '../../interfaces/user'
let token = '' let user: userPayload
describe('DELETE /user/delete', () => { describe('DELETE /user/delete', () => {
beforeAll(async () => { beforeAll(async () => {
const user = await signUpNewUser() user = await signUpNewUser()
token = user.token ?? ''
})
afterAll(async () => {
await prisma.$disconnect()
}) })
it('should delete the user successfully', async () => { it('should delete the user successfully', async () => {
await request(app).post('/user/delete') await request(app).post('/user/delete')
.set('Authorization', `Bearer ${token}`) .set('Authorization', `Bearer ${user.token ?? ''}`)
.expect(200) .expect(200)
}) })
}) })

View file

@ -1,28 +1,24 @@
import prisma from '../../db'
import app from '../../app' import app from '../../app'
import request from 'supertest' import request from 'supertest'
import deleteUser from '../utils/delete-user'
import signUpNewUser from '../utils/create-user'
import userPayload from '../../interfaces/user'
let user: userPayload
describe('POST /user/info', () => { describe('POST /user/info', () => {
beforeAll(async () => {
user = await signUpNewUser()
})
afterAll(async () => { afterAll(async () => {
await prisma.user.deleteMany({ await deleteUser(user.username ?? '')
where: {
username: 'dummmyuser5'
}
})
await prisma.$disconnect()
}) })
it('should respond with 200 status code and return the user data', async () => { it('should respond with 200 status code and return the user data', async () => {
await prisma.user.create({ const response = await request(app).get(`/user/info?u=${user.username ?? ''}`).expect(200)
data: {
username: 'dummmyuser5',
email: 'random3@email.com',
password: 'pass'
}
})
const response = await request(app).get('/user/info?u=dummmyuser5').expect(200)
expect(response.body).toHaveProperty('profileImage')
expect(response.body).toHaveProperty('displayName') expect(response.body).toHaveProperty('displayName')
expect(response.body).toHaveProperty('username') expect(response.body).toHaveProperty('username')
expect(response.body).toHaveProperty('createdAt') expect(response.body).toHaveProperty('createdAt')

View file

@ -1,83 +1,38 @@
import request from 'supertest' import request from 'supertest'
import prisma from '../../db'
import app from '../../app' import app from '../../app'
import deleteUser from '../utils/delete-user'
import signUpNewUser from '../utils/create-user'
import userPayload from '../../interfaces/user'
const mockUser = { let user: userPayload
username: 'dummmyuser1',
email: 'random@email.com',
password: 'totallysafepass'
}
describe('POST /user/signup', () => { describe('POST /user/signup', () => {
it('should respond with a 200 status code', async () => { beforeAll(async () => {
const response = await request(app).post('/user/signup').send(mockUser).expect(200) user = await signUpNewUser()
delete user.token
})
expect(response.body).toHaveProperty('displayName') afterAll(async () => {
expect(response.body).toHaveProperty('username') await deleteUser(user.username ?? '')
expect(response.body).toHaveProperty('createdAt')
}) })
it('should respond with a 400 status code if sent any invalid data', async () => { it('should respond with a 400 status code if sent any invalid data', async () => {
await request(app).post('/user/signup').send({ await request(app).post('/user/signup').send({
username: 'username12@', username: 'username12@',
email: mockUser.email, email: user.email,
password: mockUser.password password: user.password
}).expect(400) }).expect(400)
}) })
it('should respond with a 400 status code for an existing username', async () => { it('should respond with a 400 status code for an existing username or email', async () => {
await prisma.user.create({ await request(app).post('/user/signup').send({
data: { username: user.username,
username: 'dummmyuser2', email: user.email,
email: 'user@email.com', password: user.password
password: 'reallystrongpass'
}
})
const response = await request(app).post('/user/signup').send({
username: 'dummmyuser2',
email: 'user1@email.com',
password: 'reallystrongpass'
}).expect(400) }).expect(400)
expect(response.body).toHaveProperty('error')
})
it('should respond with a 400 status code for an existing email', async () => {
await prisma.user.create({
data: {
username: 'dummmyuser3',
email: 'user13@email.com',
password: '1234'
}
})
const response = await request(app).post('/user/signup').send({
username: 'dummmyuser4',
email: 'user13@email.com',
password: '12345'
}).expect(400)
expect(response.body).toHaveProperty('error')
}) })
it('should respond with a 400 status code if receive an empty body', async () => { it('should respond with a 400 status code if receive an empty body', async () => {
const response = await request(app).post('/user/signup').send({}).expect(400) await request(app).post('/user/signup').send({}).expect(400)
expect(response.body).toHaveProperty('error')
}) })
}) })
afterAll(async () => {
const usersToDelete = ['dummmyuser1', 'dummmyuser2', 'dummmyuser3', 'dummmyuser4']
await prisma.user.deleteMany({
where: {
username: {
in: usersToDelete
}
}
})
await prisma.$disconnect()
})

View file

@ -1,26 +1,18 @@
import request from 'supertest' import request from 'supertest'
import app from '../../app' import app from '../../app'
import prisma from '../../db'
import signUpNewUser from '../utils/create-user' import signUpNewUser from '../utils/create-user'
import deleteUser from '../utils/delete-user'
import userPayload from '../../interfaces/user'
let token = ''; let username = '' let user: userPayload
describe('PUT /user/update', () => { describe('PUT /user/update', () => {
beforeAll(async () => { beforeAll(async () => {
const user = await signUpNewUser() user = await signUpNewUser()
username = user.username ?? ''
token = user.token ?? ''
}) })
afterAll(async () => { afterAll(async () => {
await prisma.user.deleteMany({ await deleteUser(user.username ?? '')
where: {
username
}
})
await prisma.$disconnect()
}) })
it('should update the user successfully', async () => { it('should update the user successfully', async () => {
@ -31,7 +23,7 @@ describe('PUT /user/update', () => {
const response = await request(app) const response = await request(app)
.put('/user/update') .put('/user/update')
.send(fieldsToUpdate) .send(fieldsToUpdate)
.set('Authorization', `Bearer ${token}`).expect(200) .set('Authorization', `Bearer ${user.token ?? ''}`).expect(200)
expect(response.body).toEqual(expect.objectContaining({ expect(response.body).toEqual(expect.objectContaining({
displayName: expect.any(String), displayName: expect.any(String),

View file

@ -7,20 +7,20 @@ async function signUpNewUser (): Promise<userPayload> {
// To avoid conflicts with existing usernames or emails // To avoid conflicts with existing usernames or emails
const username = faker.internet.userName({ lastName: 'doe' }).toLowerCase() const username = faker.internet.userName({ lastName: 'doe' }).toLowerCase()
const email = faker.internet.email() const email = faker.internet.email()
const password = faker.internet.password() const password = faker.internet.password() + '@1'
await request(app).post('/user/signup').send({ await request(app).post('/user/signup').send({
username, username,
email, email,
password password
}) }).expect(200)
const response = await request(app) const response = await request(app)
.post('/user/auth') .post('/user/auth')
.send({ .send({
email, email,
password password
}) }).expect(200)
return { return {
username, username,

View file

@ -0,0 +1,18 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import prisma from '../../clients/prisma-client'
export default async function deleteUser (username: string) {
await prisma.post.deleteMany({
where: {
author: {
username
}
}
})
await prisma.user.deleteMany({
where: {
username
}
})
}

View file

@ -29,7 +29,8 @@
/* Specify a set of entries that re-map imports to additional lookup locations. */ /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
"typeRoots": [ "typeRoots": [
"src/@types", "src/@types/express.d.ts",
"src/@types/global.d.ts",
"node_modules/@types" "node_modules/@types"
], /* Specify multiple folders that act like './node_modules/@types'. */ ], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */ // "types": [], /* Specify type package names to be included without being referenced in a source file. */