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 202] BE CONTROLLER TESTS - deleteUserByEmail #174

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
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import app from '../../../app';
import request, { Response } from 'supertest';
import User from '../../../models/userModel';

const testEmail = '[email protected]';
const nonExistentEmail = '[email protected]';
const testPassword = 'password123';

const createUser = async () => {
const user = await User.create({
firstName: 'John',
lastName: 'Doe',
email: testEmail,
password: testPassword,
});
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.deleteUserByEmail', () => {
const baseUrl = '/api/users';

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

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

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

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

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

beforeEach(async () => {
await User.deleteMany();
const user = await createUser();
console.log('user: ', user);
console.log('user email: ', user.email);
console.log('test email: ', testEmail);
authCookie = await loginAndGetCookie();
});

it('🧪 Deletes the user successfully with a 200 status', async () => {
successResponse = await request(app)
.delete(`${baseUrl}/${testEmail}`)
.set('Cookie', authCookie)
.send();

expect(successResponse.status).toEqual(200);
expect(successResponse.body.msg).toEqual('User successfully deleted!');

const user = await User.findOne({ email: testEmail });
expect(user).toBeNull();
});
});
});
Original file line number Diff line number Diff line change
@@ -1,28 +1,21 @@
import User from '../../../models/userModel';
import { Request, Response, NextFunction } from 'express';
import { Request, Response } from 'express';
import { NotFoundError } from '../../../errors';
import { UserType } from '../../../types/user';

// ENDPOINT DELETE api/users/:email
// PURPOSE Delete user by email
// ACCESS Private
const deleteUserByEmail = async (req: Request, res: Response, next: NextFunction) => {
const deleteUserByEmail = async (req: Request, res: Response) => {
const { email } = req.params;

try {
const user: UserType | null = await User.findOneAndDelete({ email });
const user: UserType | null = await User.findOneAndDelete({ email });

if (!user) {
return res.status(404).json({ msg: 'User not found!' }); //TODO Move to global error handler
}

return res.status(200).json({ msg: 'User successfully deleted!' });
} catch (error) {
return next({
log: 'Express error in getUserByEmail Middleware',
status: 500,
message: { err: 'An error occurred during removal' },
});
if (!user) {
throw new NotFoundError();
}

return res.status(200).json({ msg: 'User successfully deleted!' });
};

export default deleteUserByEmail;
8 changes: 2 additions & 6 deletions server/routes/userRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import express from 'express';
import { protect } from '../middleware/authMiddleware';
import registerUser from '../controllers/userController/registerUser/registerUser';
import {
authUser,
getUserById,
// deleteUserByEmail,
} from '../controllers/userController';
import { authUser, getUserById, deleteUserByEmail } from '../controllers/userController';

const router = express.Router();

Expand All @@ -15,6 +11,6 @@ router.post('/register', registerUser);
router.use(protect); /* Require Auth for ALL routes below */
router.get('/:userId', getUserById);
//TODO Disabled until admin auth is created
//router.delete("/:email", deleteUserByEmail);
router.delete('/:email', deleteUserByEmail);

export default router;
Loading