globleerrorhandler
Version:
"Simplify error handling in Express.js using this libarary.🚀"
70 lines (58 loc) • 2.41 kB
JavaScript
const { AppError, globleHandler } = require('../index');
const httpMocks = require('node-mocks-http');
describe('AppError', () => {
it('should create an instance of AppError with correct properties', () => {
const message = 'Test error message';
const statusCode = 404;
const appError = new AppError(message, statusCode);
expect(appError).toBeInstanceOf(AppError);
expect(appError.message).toBe(message);
expect(appError.statusCode).toBe(statusCode);
expect(appError.status).toBe('fail');
expect(appError.isOperational).toBe(true);
});
});
describe('globleHandler', () => {
it('should handle errors and respond with default error structure', () => {
const err = new AppError('Test error', 404);
const req = httpMocks.createRequest();
const res = httpMocks.createResponse();
const next = jest.fn();
globleHandler()(err, req, res, next);
const data = JSON.parse(res._getData());
expect(res.statusCode).toBe(404);
expect(data.status).toBe('fail');
expect(data.message).toBe('Test error');
expect(data.stack).toBeUndefined();
expect(data.path).toBeUndefined();
expect(next).toHaveBeenCalled();
});
it('should include stack trace in the response when stack option is true', () => {
const err = new AppError('Test error', 404);
const req = httpMocks.createRequest();
const res = httpMocks.createResponse();
const next = jest.fn();
globleHandler({ stack: true })(err, req, res, next);
const data = JSON.parse(res._getData());
expect(res.statusCode).toBe(404);
expect(data.status).toBe('fail');
expect(data.message).toBe('Test error');
expect(data.stack).toBeDefined();
expect(data.path).toBeUndefined();
expect(next).toHaveBeenCalled();
});
it('should include only the path causing the error in the response when onlyPath option is true', () => {
const err = new AppError('Test error', 404);
const req = httpMocks.createRequest();
const res = httpMocks.createResponse();
const next = jest.fn();
globleHandler({ onlyPath: true })(err, req, res, next);
const data = JSON.parse(res._getData());
expect(res.statusCode).toBe(404);
expect(data.status).toBe('fail');
expect(data.message).toBe('Test error');
expect(data.stack).toBeUndefined();
expect(data.path).toBeDefined();
expect(next).toHaveBeenCalled();
});
});