Skip to content

Commit

Permalink
Merge pull request #1207 from PierreBrisorgueil/refactorImproveCoverage
Browse files Browse the repository at this point in the history
refactor(global): improve coverage ♻️
  • Loading branch information
PierreBrisorgueil authored Feb 7, 2021
2 parents ac6ba7b + 047968b commit c93d1e0
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 28 deletions.
27 changes: 3 additions & 24 deletions lib/helpers/errors.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
/**
* Module dependencies
*/
const path = require('path');

const config = require(path.resolve('./config'));

/**
* @desc Function to parse error message
* @param {Object} err
Expand All @@ -26,7 +19,7 @@ const getUniqueMessage = (err) => {
}
const fieldName = err.errmsg.substring(begin, err.errmsg.lastIndexOf('_1'));
output = `${fieldName.charAt(0).toUpperCase() + fieldName.slice(1)} already exists`;
} catch (ex) {
} catch (err) {
output = 'Unique field already exists';
}

Expand All @@ -41,19 +34,9 @@ const getUniqueMessage = (err) => {
const getMessageFromCode = (err) => {
let output;
switch (err.code) {
case 11000:
case 11001:
output = getUniqueMessage(err);
break;
case 'UNSUPPORTED_MEDIA_TYPE':
output = 'Unsupported filetype.';
break;
case 'LIMIT_FILE_SIZE':
output = `Image file too large. Maximum size allowed is ${(config.uploads.profile.avatar.limits.fileSize / (1024 * 1024)).toFixed(2)} Mb files.`;
break;
case 'LIMIT_UNEXPECTED_FILE':
output = 'Missing `newProfilePicture` field.';
break;
default: {
if (err.message) output = err.message;
else output = 'Something went wrong.';
Expand All @@ -63,28 +46,24 @@ const getMessageFromCode = (err) => {
};

/**
* @desc Function to map an array of errors
* @desc Function to map an array/object of errors
* @param {Object} err
* @return {String} message
*/
const getMessageFromErrors = (err) => {
if (err instanceof Array) return err.errors;
let output = '';
if (err.errors instanceof Array) {
err.errors.map((error) => {
err.errors.forEach((error) => {
if (error.message) {
output += `${error.message} `;
}
return null;
});
} else if (err.errors instanceof Object) {
Object.keys(err.errors).forEach((key) => {
if (err.errors[key].message) {
output += `${err.errors[key].message} `;
}
});
} else {
output = err.message;
}
return output;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const logger = require(path.resolve('./lib/services/logger'));
const mongooseService = require(path.resolve('./lib/services/mongoose'));
const multerService = require(path.resolve('./lib/services/multer'));
const seed = require(path.resolve('./lib/services/seed'));
const errors = require(path.resolve('./lib/helpers/errors'));

/**
* Unit tests
Expand Down Expand Up @@ -396,6 +397,36 @@ describe('Configuration Tests:', () => {
});
});

describe('Errors', () => {
test('should return errors message properly', async () => {
try {
const fromCode = errors.getMessage({ code: 11001, errmsg: 'test' });
expect(fromCode).toBe('Test already exists.');

const fromCode2 = errors.getMessage({ code: 11001, errmsg: 'test.$.test' });
expect(fromCode2).toBe('Test.$ already exists.');

const fromCodeUnknow = errors.getMessage({ code: 'unknow' });
expect(fromCodeUnknow).toBe('Something went wrong.');

const fromErrorsArray = errors.getMessage({ errors: [{ message: 'error1' }, { message: 'error2' }] });
expect(fromErrorsArray).toBe('error1 error2 .');

const fromErrorsObject = errors.getMessage({ errors: { one: { message: 'error1' }, two: { message: 'error2' } } });
expect(fromErrorsObject).toBe('error1 error2 .');

const fromMessage = errors.getMessage({ message: 'error1' });
expect(fromMessage).toBe('error1.');

const fromEmpty = errors.getMessage({ });
expect(fromEmpty).toBe('error while retrieving the error :o : {}.');
} catch (err) {
console.log(err);
expect(err).toBeFalsy();
}
});
});

// Mongoose disconnect
afterAll(() => mongooseService.disconnect()
.catch((e) => {
Expand Down
1 change: 0 additions & 1 deletion modules/uploads/controllers/uploads.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@ exports.uploadByImageName = async (req, res, next, uploadImageName) => {
req.sharpOption = opts[2] || null;
next();
} catch (err) {
console.log('err', err);
next(err);
}
};
2 changes: 0 additions & 2 deletions modules/users/repositories/user.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ exports.get = (user) => {
},
}).exec();
}
return null;
};

/**
Expand All @@ -75,7 +74,6 @@ exports.update = (user) => new User(user).save();
exports.delete = async (user) => {
if (user.id && mongoose.Types.ObjectId.isValid(user.id)) return User.deleteOne({ _id: user.id }).exec();
if (user.email) return User.deleteOne({ email: user.email }).exec();
return null;
};

/**
Expand Down
12 changes: 11 additions & 1 deletion modules/users/tests/user.crud.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,7 @@ describe('User CRUD Tests :', () => {
}
});

test('should be able to update Terms sign date', async () => {
test('should be able to update Terms sign date if logged in', async () => {
try {
const result = await agent.get('/api/users/terms')
.expect(200);
Expand Down Expand Up @@ -1029,6 +1029,16 @@ describe('User CRUD Tests :', () => {
});

describe('Logout', () => {
test('should not be able to update Terms sign date if not logged in', async () => {
try {
await agent.get('/api/users/terms')
.expect(401);
} catch (err) {
expect(err).toBeFalsy();
console.log(err);
}
});

test('should not be able to change user own password if not signed in', async () => {
try {
await agent.post('/api/users/password')
Expand Down

0 comments on commit c93d1e0

Please sign in to comment.