Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CHE 201] BE CONTROLLER TESTS - getUserById #164

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions server/controllers/userController/getUserById/getUserById.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import app from '../../../app';
import request, { Response } from 'supertest';
import User from '../../../models/userModel';

const invalidUserId = 'invalidUserId123';
const nonExistentUserId = '5f8f8c44b54764421b7156c4';
const testEmail = '[email protected]';
const testPassword = 'password123';

const createUser = async () => {
const user = await User.create({
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
password: 'password123',
});
return user;
};

const loginAndGetCookie = async () => {
const response = await request(app)
.post('/api/users/login')
.send({ email: testEmail, password: testPassword });
return response.headers['set-cookie'];
};

describe('Tests for userController.getUserById', () => {
const baseUrl = '/api/users';

describe('Get User By Id Failure Tests', () => {
let authCookie: string;

beforeEach(async () => {
await User.deleteMany();
await createUser();
authCookie = await loginAndGetCookie();
});

it('🧪 Fails if userId is invalid', async () => {
const response = await request(app)
.get(`${baseUrl}/${invalidUserId}`)
.set('Cookie', authCookie)
.send();

expect(response.status).toEqual(400);
expect(response.body[0].message).toEqual('Invalid user ID format');
expect(response.body[0].field).toEqual('user ID');
});

it('🧪 Fails if user is not found', async () => {
const response = await request(app)
.get(`${baseUrl}/${nonExistentUserId}`)
.set('Cookie', authCookie)
.send();

expect(response.status).toEqual(404);
expect(response.body[0].message).toEqual('Not Found');
});
});

describe('Get User By Id Success Tests', () => {
let successResponse: Response;
let authCookie: string;

it('🧪 Retrieves the user successfully with a 200 status', async () => {
await User.deleteMany();
const user = await createUser();
authCookie = await loginAndGetCookie();
successResponse = await request(app)
.get(`${baseUrl}/${user.id}`)
.set('Cookie', authCookie)
.send();
expect(successResponse.status).toEqual(200);
expect(successResponse.body._id).toEqual(user.id);
expect(successResponse.body.email).toEqual('[email protected]');
});
});
});
27 changes: 12 additions & 15 deletions server/controllers/userController/getUserById/getUserById.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
import mongoose from 'mongoose';
import User from '../../../models/userModel';
import { Request, Response, NextFunction } from 'express';
import { Request, Response } from 'express';
import { NotFoundError, ValidationError, RequestValidationError } from '../../../errors';
import { UserType } from '../../../types/user';

// ENDPOINT GET api/users/:userId
// PURPOSE Get user by id
// ACCESS Private
const getUserById = async (req: Request, res: Response, next: NextFunction) => {
const getUserById = async (req: Request, res: Response) => {
const { userId } = req.params;
if (!mongoose.Types.ObjectId.isValid(userId)) {
throw new RequestValidationError([new ValidationError('Invalid user ID format', 'user ID')]);
}

try {
const user: UserType | null = await User.findOne({ _id: userId });
const user: UserType | null = await User.findOne({ _id: userId });

if (!user) {
return res.status(401).json({ msg: 'User not found!' }); //TODO Move to global error handler
}
res.locals.user = user;
return res.status(200).json(res.locals.user);
} catch (error) {
return next({
log: 'Express error in getUserById Middleware',
status: 500,
message: { err: 'An error occurred during retrieval' },
});
if (!user) {
throw new NotFoundError();
}
res.locals.user = user;
return res.status(200).json(res.locals.user);
};

export default getUserById;
Loading