Skip to content

Commit

Permalink
ajout test unitaire pour le middleware et les controllers posts et auth
Browse files Browse the repository at this point in the history
  • Loading branch information
julienmeire committed Mar 28, 2024
1 parent 484ebf4 commit 55a323f
Show file tree
Hide file tree
Showing 4,618 changed files with 592,126 additions and 893 deletions.
The diff you're trying to view is too large. We only load the first 3000 changed files.
141 changes: 141 additions & 0 deletions backend/controllers/auth.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
const { signup, login } = require('./auth');
const User = require('../models/user');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

jest.mock('../models/user', () => ({
save: jest.fn(),
find: jest.fn(),
}));

jest.mock('bcryptjs', () => ({
hash: jest.fn(),
compare: jest.fn(),
}));

jest.mock('jsonwebtoken', () => ({
sign: jest.fn(),
}));

describe('signup', () => {
let req, res, next;
beforeEach(() => {
req = {
body: {
name: 'Test User',
email: 'test@example.com',
password: 'password123',
},
};
res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
};
next = jest.fn();
});

it('should create a new user and return success message', async () => {
User.save.mockResolvedValue();
const hashedPassword = bcrypt.hash(req.body.password, 10);

await signup(req, res, next);

expect(User.save).toHaveBeenCalledWith({
name: req.body.name,
email: req.body.email,
password : hashedPassword,
});
expect(res.status).toHaveBeenCalledWith(201);
expect(res.json).toHaveBeenCalledWith({ message: 'Utilisateur enregistré' });
});

it('should handle errors', async () => {
const errorMessage = 'Test Error';
User.save.mockRejectedValue(new Error(errorMessage));

await signup(req, res, next);

expect(next).toHaveBeenCalledWith(expect.any(Error));
expect(next.mock.calls[0][0].message).toBe(errorMessage);
});
});

describe('login', () => {
let req, res, next;
beforeEach(() => {
req = {
body: {
email: 'test@example.com',
password: 'password123',
},
};
res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
};
next = jest.fn();
});

it('should login successfully and return token and user id', async () => {
const storedUser = {
id: 'testUserId',
email: 'test@example.com',
password: 'hashedPassword',
};
User.find.mockResolvedValue([[storedUser]]);

bcrypt.compare.mockResolvedValue(true);

jwt.sign.mockReturnValue('testToken');

await login(req, res, next);

expect(User.find).toHaveBeenCalledWith(req.body.email);
expect(bcrypt.compare).toHaveBeenCalledWith(req.body.password, storedUser.password);
expect(jwt.sign).toHaveBeenCalledWith(
{
email: storedUser.email,
userId: storedUser.id,
},
'secretfortoken',
{ expiresIn: '1h' }
);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith({ token: 'testToken', userId: 'testUserId' });
});

it('should handle no user found', async () => {
User.find.mockResolvedValue([[]]);

await login(req, res, next);

expect(next).toHaveBeenCalledWith(expect.any(Error));
expect(next.mock.calls[0][0].statusCode).toBe(401);
});

it('should handle incorrect password', async () => {
const storedUser = {
id: 'testUserId',
email: 'test@example.com',
password: 'hashedPassword',
};
User.find.mockResolvedValue([[storedUser]]);

bcrypt.compare.mockResolvedValue(false);

await login(req, res, next);

expect(next).toHaveBeenCalledWith(expect.any(Error));
expect(next.mock.calls[0][0].statusCode).toBe(401);
});

it('should handle errors', async () => {
const errorMessage = 'Test Error';
User.find.mockRejectedValue(new Error(errorMessage));

await login(req, res, next);

expect(next).toHaveBeenCalledWith(expect.any(Error));
expect(next.mock.calls[0][0].message).toBe(errorMessage);
});
});
102 changes: 102 additions & 0 deletions backend/controllers/posts.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
const { fetchAll, postPost, deletePost } = require('./posts');
const Post = require('../models/posts');

jest.mock('express-validator', () => ({
validationResult: jest.fn(() => ({
isEmpty: jest.fn(() => true),
})),
}));

jest.mock('../models/posts', () => ({
fetchAll: jest.fn(),
save: jest.fn(),
delete: jest.fn(),
}));

describe('Controller Tests', () => {
let req, res, next;

beforeEach(() => {
req = {
body: {},
params: {},
};
res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
};
next = jest.fn();
});

describe('fetchAll', () => {
it('should fetch all posts successfully', async () => {
const allPosts = [{ id: 1, title: 'Post 1' }, { id: 2, title: 'Post 2' }];
Post.fetchAll.mockResolvedValue([allPosts]);

await fetchAll(req, res, next);

expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(allPosts);
});

it('should handle errors during fetchAll', async () => {
const error = new Error('Database error');
Post.fetchAll.mockRejectedValue(error);

await fetchAll(req, res, next);

expect(next).toHaveBeenCalledWith(error);
});
});

describe('postPost', () => {
it('should create a new post successfully', async () => {
const newPost = {
title: 'New Post',
body: 'Body of the new post',
user: 'User123',
};
req.body = newPost;
Post.save.mockResolvedValue();

await postPost(req, res, next);

expect(Post.save).toHaveBeenCalledWith(newPost);
expect(res.status).toHaveBeenCalledWith(201);
expect(res.json).toHaveBeenCalledWith({ message: ' publication réussi ' });
});

it('should handle errors during postPost', async () => {
const error = new Error('Database error');
Post.save.mockRejectedValue(error);

await postPost(req, res, next);

expect(next).toHaveBeenCalledWith(error);
});
});

describe('deletePost', () => {
it('should delete a post successfully', async () => {
const postId = '123';
req.params.id = postId;
const deleteResponse = { message: 'Post deleted successfully' };
Post.delete.mockResolvedValue(deleteResponse);

await deletePost(req, res, next);

expect(Post.delete).toHaveBeenCalledWith(postId);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(deleteResponse);
});

it('should handle errors during deletePost', async () => {
const error = new Error('Database error');
Post.delete.mockRejectedValue(error);

await deletePost(req, res, next);

expect(next).toHaveBeenCalledWith(error);
});
});
});
66 changes: 66 additions & 0 deletions backend/middleware/testMiddleware.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
const jwt = require('jsonwebtoken');
const middleware = require('./auth');

describe('Auth Middleware', () => {
it('should throw an error if no authorization header is present', () => {
const req = {
get: jest.fn().mockReturnValue(undefined)
};
expect(() => middleware(req, {}, () => {})).toThrow('Utilisateur non enregistré');
});

it('should throw an error if the authorization header is malformed', () => {
const req = {
get: jest.fn().mockReturnValue('Bearer')
};
expect(() => middleware(req, {}, () => {})).toThrow('jwt must be provided');
});

it('should throw an error if the token cannot be verified', () => {
const req = {
get: jest.fn().mockReturnValue('Bearer invalidtoken')
};
expect(() => middleware(req, {}, () => {})).toThrow('jwt malformed');
});

it('should set req.isLoggedIn to true if token is valid', () => {
const decodedToken = {
userId: 'user123',
email: 'test@example.com'
};
const req = {
get: jest.fn().mockReturnValue('Bearer validtoken'),
};
jwt.verify = jest.fn().mockReturnValue(decodedToken);
middleware(req, {}, () => {});
expect(req.isLoggedIn).toBe(true);
});

it('should set req.userId and req.email if token is valid', () => {
const decodedToken = {
userId: 'user123',
email: 'test@example.com'
};
const req = {
get: jest.fn().mockReturnValue('Bearer validtoken'),
};
jwt.verify = jest.fn().mockReturnValue(decodedToken);
middleware(req, {}, () => {});
expect(req.userId).toBe(decodedToken.userId);
expect(req.email).toBe(decodedToken.email);
});

it('should call next() if token is valid', () => {
const decodedToken = {
userId: 'user123',
email: 'test@example.com'
};
const req = {
get: jest.fn().mockReturnValue('Bearer validtoken'),
};
jwt.verify = jest.fn().mockReturnValue(decodedToken);
const nextMock = jest.fn();
middleware(req, {}, nextMock);
expect(nextMock).toHaveBeenCalled();
});
});
16 changes: 16 additions & 0 deletions backend/node_modules/.bin/_mocha

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions backend/node_modules/.bin/_mocha.cmd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 28 additions & 0 deletions backend/node_modules/.bin/_mocha.ps1

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions backend/node_modules/.bin/browserslist

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 55a323f

Please sign in to comment.