Skip to content

Commit

Permalink
update testing mock
Browse files Browse the repository at this point in the history
  • Loading branch information
jsuyog2 committed Aug 13, 2024
1 parent d3fa18f commit df3cc59
Show file tree
Hide file tree
Showing 9 changed files with 121 additions and 118 deletions.
114 changes: 57 additions & 57 deletions junit.xml

Large diffs are not rendered by default.

27 changes: 0 additions & 27 deletions key/private.key

This file was deleted.

9 changes: 0 additions & 9 deletions key/public.key

This file was deleted.

42 changes: 42 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"globals": "^15.9.0",
"jest": "^29.7.0",
"jest-junit": "^16.0.0",
"mongoose-mock": "^0.4.0",
"node-mocks-http": "^1.15.1",
"nodemailer-mock": "^2.0.6",
"supertest": "^7.0.0",
Expand Down
8 changes: 5 additions & 3 deletions test/auth.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

require('dotenv').config();
const fs = require('fs');
const path = require('path');
const httpMocks = require('node-mocks-http');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
Expand All @@ -33,14 +34,15 @@ const authController = require('./../controllers/auth.controller');
jest.mock('bcrypt');
jest.mock('jsonwebtoken');
jest.mock('../utils/emailService');

jest.mock('mongoose', () => require('mongoose-mock'));
/**
* @description Unit tests for the login function of the auth controller.
*/
describe('Auth Controller', () => {

let req, res;
const orignalFs = fs.readFileSync
const orignalPath = path.resolve
beforeEach(() => {
const mockPublicKey = 'mockPublicKeyContent';
fs.readFileSync = jest.fn().mockResolvedValue(mockPublicKey)
Expand All @@ -50,7 +52,7 @@ describe('Auth Controller', () => {

afterEach(async () => {
fs.readFileSync = orignalFs;
await db.mongoose.connection.close();
path.resolve = orignalPath;
jest.clearAllMocks();
});

Expand All @@ -65,7 +67,7 @@ describe('Auth Controller', () => {
db.user.findOne = jest.fn().mockResolvedValue(mockUser);
db.session.create = jest.fn();
jwt.sign.mockReturnValue('mocktoken');

path.resolve = jest.fn().mockResolvedValue('/./');
await authController.login(req, res);

expect(res.statusCode).toBe(200);
Expand Down
32 changes: 13 additions & 19 deletions test/middlewares.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,23 @@

require('dotenv').config();
const fs = require('fs');
const path = require('path');
const httpMocks = require('node-mocks-http');
const { validationResult } = require('express-validator');
const { verifyToken, logger, roleAuthorization, validationErrorHandler } = require('../middlewares'); // Adjust the path as needed
const jwt = require('jsonwebtoken');
const db = require('../models');

jest.mock('express-validator');

jest.mock('mongoose', () => require('mongoose-mock'));
/**
* @description Unit tests for the verifyToken middleware function.
* This middleware verifies JWT tokens, checks for token validity, blacklist status, and associated user information.
*/
describe('verifyToken Middleware', () => {
let req, res, next;
const orignalFs = fs.readFileSync
const orignalPath = path.resolve
beforeEach(() => {
const mockPublicKey = 'mockPublicKeyContent';
fs.readFileSync = jest.fn().mockResolvedValue(mockPublicKey)
Expand All @@ -43,7 +45,7 @@ describe('verifyToken Middleware', () => {
});

afterEach(async () => {
await db.mongoose.connection.close();
path.resolve = orignalPath;
fs.readFileSync = orignalFs;
})

Expand Down Expand Up @@ -73,7 +75,7 @@ describe('verifyToken Middleware', () => {
jwt.verify = jest.fn((token, publicKey, options, callback) => {
callback(new Error('Invalid token'), null);
});

jest.spyOn(path, 'resolve').mockReturnValueOnce('/fakepath');
verifyToken(req, res, next);

setTimeout(() => {
Expand All @@ -94,7 +96,7 @@ describe('verifyToken Middleware', () => {
jwt.verify = jest.fn((token, publicKey, options, callback) => {
callback(null, {});
});

jest.spyOn(path, 'resolve').mockReturnValueOnce('/fakepath');
verifyToken(req, res, next);

setTimeout(() => {
Expand All @@ -117,7 +119,7 @@ describe('verifyToken Middleware', () => {
});

db.session.findOne = jest.fn().mockResolvedValue({ flag: true });

jest.spyOn(path, 'resolve').mockReturnValueOnce('/fakepath');
verifyToken(req, res, next);

setTimeout(() => {
Expand All @@ -142,7 +144,7 @@ describe('verifyToken Middleware', () => {
db.session.findOne = jest.fn().mockResolvedValue({ flag: false });

db.user.findOne = jest.fn().mockResolvedValue(null); // User not found

jest.spyOn(path, 'resolve').mockReturnValueOnce('/fakepath');
verifyToken(req, res, next);

setTimeout(() => {
Expand All @@ -153,9 +155,9 @@ describe('verifyToken Middleware', () => {
});

/**
* @description Test case for successful token verification.
* The middleware should attach user information to req and call next().
*/
* @description Test case for successful token verification.
* The middleware should attach user information to req and call next().
*/
it('should attach user info to req and call next() if the token is valid and user is found', (done) => {
const mockToken = 'validtoken';
req.headers.authorization = `Bearer ${mockToken}`;
Expand All @@ -175,6 +177,7 @@ describe('verifyToken Middleware', () => {
db.user_roles.find = jest.fn().mockReturnValue({
populate: jest.fn().mockResolvedValue(userRoles)
});
jest.spyOn(path, 'resolve').mockReturnValueOnce('/fakepath');
verifyToken(req, res, next);

setTimeout(() => {
Expand Down Expand Up @@ -203,7 +206,7 @@ describe('verifyToken Middleware', () => {
callback(null, { id: 1, username: 'testuser' });
});
db.session.findOne.mockRejectedValue(mockError);

jest.spyOn(path, 'resolve').mockReturnValueOnce('/fakepath');
verifyToken(req, res, next);
setTimeout(() => {
expect(res.statusCode).toBe(401);
Expand All @@ -230,9 +233,6 @@ describe('logger Middleware', () => {
res = httpMocks.createResponse();
next = jest.fn();
});
afterEach(async () => {
await db.mongoose.connection.close();
})
/**
* @description Test case for logging request details to the database.
*/
Expand Down Expand Up @@ -323,9 +323,6 @@ describe('roleAuthorization Middleware', () => {
res = httpMocks.createResponse();
next = jest.fn();
});
afterEach(async () => {
await db.mongoose.connection.close();
})

/**
* @description Test case for allowing access when the user has the required role.
Expand Down Expand Up @@ -378,9 +375,6 @@ describe('validationErrorHandler Middleware', () => {
res = httpMocks.createResponse();
next = jest.fn();
});
afterEach(async () => {
await db.mongoose.connection.close();
})
/**
* @description Test case for handling validation errors.
* The middleware should return a 400 status with the error details.
Expand Down
3 changes: 2 additions & 1 deletion test/role.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@ const roleController = require('../controllers/role.controller');
const db = require('../models');
const httpMocks = require('node-mocks-http');

jest.mock('mongoose', () => require('mongoose-mock'));

describe('Role Controller', () => {
beforeEach(() => {
jest.clearAllMocks();
});

afterEach(async () => {
await db.mongoose.connection.close();
jest.clearAllMocks();
});

Expand Down
3 changes: 1 addition & 2 deletions test/user.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const userController = require('../controllers/user.controller');
const db = require('../models');
const bcrypt = require('bcrypt');
const httpMocks = require('node-mocks-http');

jest.mock('mongoose', () => require('mongoose-mock'));
describe('User Controller', () => {
let userMock;

Expand Down Expand Up @@ -57,7 +57,6 @@ describe('User Controller', () => {
});

afterEach(async () => {
await db.mongoose.connection.close();
jest.clearAllMocks();
});

Expand Down

0 comments on commit df3cc59

Please sign in to comment.