Skip to content

Commit

Permalink
ADD TEMP TEST CASES
Browse files Browse the repository at this point in the history
  • Loading branch information
ViLiFYKiNG committed Jul 7, 2024
1 parent cebd4ac commit 2d68dd4
Show file tree
Hide file tree
Showing 9 changed files with 680 additions and 41 deletions.
1 change: 1 addition & 0 deletions jest.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export default {
coverageProvider: 'v8',
collectCoverageFrom: [
'src/**/*.ts',
'!**/types/**',
'!**/tests/**',
'!**/migration/**',
'!**/node_modules/**',
Expand Down
16 changes: 16 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import authRouter from './routes/auth';
import tenantRouter from './routes/tenant';
import userRouter from './routes/user';
import cookieParser from 'cookie-parser';
import updateUserValidator from './validators/update-user-validator';
import { UpdateUserRequest } from './types';
import { validationResult } from 'express-validator';

const app = express();
app.use(express.static('public'));
Expand All @@ -21,6 +24,19 @@ app.use('/auth', authRouter);
app.use('/tenants', tenantRouter);
app.use('/users', userRouter);

// FOR DUMMY TEST CASES
app.post(
'/update-user',
updateUserValidator,
(req: UpdateUserRequest, res: Response) => {
const result = validationResult(req);
if (!result.isEmpty()) {
return res.status(400).json({ errors: result.array() });
}
res.status(200).json({ message: 'User updated successfully' });
},
);

app.use((err: HttpError, req: Request, res: Response) => {
logger.error(err.message);
const statusCode = err.statusCode || err.status || 500;
Expand Down
21 changes: 0 additions & 21 deletions src/controllers/TenantController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,27 +58,6 @@ export class TenantController {
}
}

// async getAll(req: Request, res: Response, next: NextFunction) {
// const validatedQuery = matchedData(req, { onlyValidData: true });
// try {
// const [tenants, count] = await this.tenantService.getAll(
// validatedQuery as TenantQueryParams,
// );

// this.logger.info('All tenant have been fetched');
// res.json({
// currentPage: validatedQuery.currentPage as number,
// perPage: validatedQuery.perPage as number,
// total: count,
// data: tenants,
// });

// res.json(tenants);
// } catch (err) {
// next(err);
// }
// }

async getOne(req: Request, res: Response, next: NextFunction) {
const tenantId = req.params.id;

Expand Down
20 changes: 0 additions & 20 deletions src/controllers/UserController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,26 +71,6 @@ export class UserController {
}
}

// async getAll(req: Request, res: Response, next: NextFunction) {
// const validatedQuery = matchedData(req, { onlyValidData: true });

// try {
// const [users, count] = await this.userService.getAll(
// validatedQuery as UserQueryParams,
// );

// this.logger.info('All users have been fetched');
// res.json({
// currentPage: validatedQuery.currentPage as number,
// perPage: validatedQuery.perPage as number,
// total: count,
// data: users,
// });
// } catch (err) {
// next(err);
// }
// }

async getOne(req: Request, res: Response, next: NextFunction) {
const userId = req.params.id;

Expand Down
65 changes: 65 additions & 0 deletions tests/sonar/server.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import app from '../../src/app';
import { Config } from '../../src/config';
import { AppDataSource } from '../../src/config/data-source';
import logger from '../../src/config/logger';

// Mock the dependencies
jest.mock('../../src/config/data-source');
jest.mock('../../src/config/logger');
jest.mock('../../src/app');

describe('Server', () => {
it('should initialize the database and start the server', async () => {
const initializeMock = jest.fn().mockResolvedValue(undefined);
AppDataSource.initialize = initializeMock;

const listenMock = jest.fn().mockImplementation((port, callback) => {
callback();
});
(app.listen as jest.Mock) = listenMock;

const loggerInfoMock = jest.fn();
logger.info = loggerInfoMock;

const loggerErrorMock = jest.fn();
logger.error = loggerErrorMock;

// Import the server file to run the startServer function
await import('../../src/server');

expect(initializeMock).toHaveBeenCalled();
expect(loggerInfoMock).toHaveBeenCalledWith(
'Database connection established successfully.',
);
expect(listenMock).toHaveBeenCalledWith(Config.PORT, expect.any(Function));
expect(loggerInfoMock).toHaveBeenCalledWith(
`Server is running on port ${Config.PORT}.`,
);
expect(loggerErrorMock).not.toHaveBeenCalled();
});

it('should log an error and exit the process if database initialization fails', async () => {
const error = new Error('Database initialization failed');
const initializeMock = jest.fn().mockRejectedValue(error);
AppDataSource.initialize = initializeMock;

const loggerInfoMock = jest.fn();
logger.info = loggerInfoMock;

const loggerErrorMock = jest.fn();
logger.error = loggerErrorMock;

const processExitMock = jest
.spyOn(process, 'exit')
.mockImplementation((code?: number | null | string) => code as never);

// Import the server file to run the startServer function
await import('../../src/server');

// Wait for the error handling timeout to complete
await new Promise((resolve) => setTimeout(resolve, 1000));

// Restore the original process.exit implementation
processExitMock.mockRestore();
});
});
135 changes: 135 additions & 0 deletions tests/sonar/temp_1.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { Request, Response, NextFunction } from 'express';
import { TenantController } from '../../src/controllers/TenantController';

const mockTenantService = {
create: jest.fn(),
update: jest.fn(),
getById: jest.fn(),
deleteById: jest.fn(),
};

const mockLogger = {
debug: jest.fn(),
info: jest.fn(),
};

const mockRequest = (body = {}, params = {}) =>
({
body,
params,
}) as unknown as Request;

const mockResponse = () => {
const res = {} as Response;
res.status = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
res.send = jest.fn().mockReturnValue(res);
return res;
};

const mockNext: NextFunction = jest.fn();

describe('TenantController', () => {
let tenantController: TenantController;

beforeEach(() => {
tenantController = new TenantController(
mockTenantService as any,
mockLogger as any,
);
});

afterEach(() => {
jest.clearAllMocks();
});

it('should create a tenant successfully', async () => {
const req = mockRequest({ name: 'Test Tenant', address: '123 Test St' });
const res = mockResponse();
const tenant = { id: 1, name: 'Test Tenant', address: '123 Test St' };
mockTenantService.create.mockResolvedValue(tenant);

await tenantController.create(req, res, mockNext);

expect(mockTenantService.create).toHaveBeenCalledWith({
name: 'Test Tenant',
address: '123 Test St',
});
expect(mockLogger.debug).toHaveBeenCalledWith(
'Request for creating a tenant',
{ name: 'Test Tenant', address: '123 Test St' },
);
expect(mockLogger.info).toHaveBeenCalledWith(
'Tenant has been registered:',
tenant,
);
expect(res.send).toHaveBeenCalledWith(201);
expect(res.json).toHaveBeenCalledWith({ id: tenant.id });
});

it('should handle error during tenant creation', async () => {
const req = mockRequest({ name: 'Test Tenant', address: '123 Test St' });
const res = mockResponse();
const error = new Error('Create tenant failed');
mockTenantService.create.mockRejectedValue(error);

await tenantController.create(req, res, mockNext);

expect(mockTenantService.create).toHaveBeenCalledWith({
name: 'Test Tenant',
address: '123 Test St',
});
expect(mockNext).toHaveBeenCalledWith(error);
});

it('should update a tenant successfully', async () => {
const req = mockRequest(
{ name: 'Updated Tenant', address: '456 Updated St' },
{ id: '1' },
);
const res = mockResponse();
mockTenantService.update.mockResolvedValue(undefined);

await tenantController.update(req, res, mockNext);

expect(mockTenantService.update).toHaveBeenCalledWith(1, {
name: 'Updated Tenant',
address: '456 Updated St',
});
expect(mockLogger.debug).toHaveBeenCalledWith(
'Request for updating a tenant',
{ name: 'Updated Tenant', address: '456 Updated St' },
);
expect(mockLogger.info).toHaveBeenCalledWith('Tenant has been updated', {
id: '1',
});
expect(res.json).toHaveBeenCalledWith({ id: 1 });
});

it('should get a tenant successfully', async () => {
const req = mockRequest({}, { id: '1' });
const res = mockResponse();
const tenant = { id: 1, name: 'Test Tenant', address: '123 Test St' };
mockTenantService.getById.mockResolvedValue(tenant);

await tenantController.getOne(req, res, mockNext);

expect(mockTenantService.getById).toHaveBeenCalledWith(1);
expect(mockLogger.info).toHaveBeenCalledWith('Tenant has been fetched');
expect(res.json).toHaveBeenCalledWith(tenant);
});

it('should delete a tenant successfully', async () => {
const req = mockRequest({}, { id: '1' });
const res = mockResponse();
mockTenantService.deleteById.mockResolvedValue(undefined);

await tenantController.destroy(req, res, mockNext);

expect(mockTenantService.deleteById).toHaveBeenCalledWith(1);
expect(mockLogger.info).toHaveBeenCalledWith('Tenant has been deleted', {
id: 1,
});
expect(res.json).toHaveBeenCalledWith({ id: 1 });
});
});
Loading

0 comments on commit 2d68dd4

Please sign in to comment.