Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/routes/account/create/controller.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Request, Response } from 'express';
import { StatusCodes } from 'http-status-codes';
import { Account } from '@/models/Account';
import createAccountController from './controller';

Expand All @@ -16,15 +17,30 @@ describe('createAccountController', () => {

it('should create a new account and return 201 status', async () => {
req.body = { name: 'Test Account' };
Account.findOne = jest.fn().mockResolvedValueOnce(null);
Account.create = jest.fn().mockResolvedValueOnce(req.body);

await createAccountController(req as Request, res as Response);

expect(res.status).toHaveBeenCalledWith(201);
expect(res.status).toHaveBeenCalledWith(StatusCodes.CREATED);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
name: 'Test Account',
})
);
});

it('should return 409 if account with the same name already exists', async () => {
req.body = { name: 'Existing Account' };
Account.findOne = jest.fn().mockResolvedValueOnce({ name: 'Existing Account' });

await createAccountController(req as Request, res as Response);

expect(res.status).toHaveBeenCalledWith(StatusCodes.CONFLICT);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
message: 'Account with this name already exists',
})
);
});
});
8 changes: 8 additions & 0 deletions src/routes/account/create/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@ import { StatusCodes } from 'http-status-codes';
import { Account } from '@/models/Account';

export default async (req: Request, res: Response) => {
const existingAccount = await Account.findOne({ name: req.body.name });

if (existingAccount) {
return res.status(StatusCodes.CONFLICT).json({
message: 'Account with this name already exists',
});
}

const account = await Account.create(req.body);

res.status(StatusCodes.CREATED).json(account);
Expand Down
55 changes: 37 additions & 18 deletions src/routes/account/credit/controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,66 +8,77 @@ describe('creditAccountController', () => {
let req: Partial<Request>;
let res: Partial<Response>;

beforeAll(() => {
Account.startSession = jest.fn().mockReturnValue({
startTransaction: jest.fn(),
commitTransaction: jest.fn(),
abortTransaction: jest.fn(),
endSession: jest.fn(),
});
});

beforeEach(() => {
req = {
params: { accountId: '123' },
body: { amount: 500, date: '2025-04-02' },
params: { accountId: 'acc123' },
body: { amount: 200, date: '2025-04-02' },
};
res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
};
});

it('should credit the account and return 200', async () => {
const accountId = '123';
const creditAmount = 500;
it('should credit the account and return the updated account and transaction', async () => {
const accountId = 'acc123';
const currentBalance = 1000;
const creditAmount = 200;
const newBalance = currentBalance + creditAmount;

const mockAccount = {
_id: accountId,
name: 'Test Account',
balance: currentBalance,
save: jest.fn().mockResolvedValueOnce({
_id: accountId,
name: 'Test Account',
balance: newBalance,
}),
};

Account.findById = jest.fn().mockResolvedValueOnce(mockAccount);
Transaction.create = jest.fn().mockResolvedValueOnce({
const mockTransaction = {
_id: 'txn123',
account: accountId,
type: TransactionType.credit,
amount: creditAmount,
balance: newBalance,
description: 'Account credit',
});
};

Account.findById = jest.fn().mockReturnValueOnce({ session: jest.fn().mockResolvedValueOnce(mockAccount) });
Transaction.create = jest.fn().mockResolvedValueOnce(mockTransaction);

await creditAccountController(req as Request, res as Response);

expect(mockAccount.save).toHaveBeenCalled();
expect(Transaction.create).toHaveBeenCalledWith(
expect.objectContaining({
account: accountId,
type: TransactionType.credit,
amount: creditAmount,
})
[
expect.objectContaining({
account: accountId,
type: TransactionType.credit,
amount: creditAmount,
}),
],
expect.any(Object)
);
expect(res.status).toHaveBeenCalledWith(StatusCodes.CREATED);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
account: expect.objectContaining({
balance: newBalance,
}),
transaction: mockTransaction,
})
);
});

it('should return 404 if account is not found', async () => {
Account.findById = jest.fn().mockResolvedValueOnce(null);
Account.findById = jest.fn().mockReturnValueOnce({ session: jest.fn().mockResolvedValueOnce(null) });

await creditAccountController(req as Request, res as Response);

Expand All @@ -78,4 +89,12 @@ describe('creditAccountController', () => {
})
);
});

it('should handle errors and abort transaction', async () => {
Account.findById = jest
.fn()
.mockReturnValueOnce({ session: jest.fn().mockRejectedValueOnce(new Error('Database error')) });

await expect(creditAccountController(req as Request, res as Response)).rejects.toThrow('Database error');
});
});
45 changes: 31 additions & 14 deletions src/routes/account/credit/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,38 @@ export default async (req: Request, res: Response) => {
const { accountId } = req.params;
const { amount, date } = req.body;

const account = await Account.findById(accountId);
if (!account) {
res.status(StatusCodes.NOT_FOUND).json({ error: 'Account not found' });
return;
}
const session = await Account.startSession();
session.startTransaction();

try {
const account = await Account.findById(accountId).session(session);
if (!account) {
await session.abortTransaction();
res.status(StatusCodes.NOT_FOUND).json({ error: 'Account not found' });
return;
}

const transaction = await Transaction.create({
amount,
date,
type: TransactionType.credit,
account: accountId,
});
const transaction = await Transaction.create(
[
{
amount,
date,
type: TransactionType.credit,
account: accountId,
},
],
{ session }
);

account.balance += amount;
await account.save();
account.balance += amount;
await account.save({ session });

res.status(StatusCodes.CREATED).json({ account, transaction });
await session.commitTransaction();
res.status(StatusCodes.CREATED).json({ account, transaction });
} catch (error) {
await session.abortTransaction();
throw error;
} finally {
session.endSession();
}
};
65 changes: 41 additions & 24 deletions src/routes/account/debit/controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,66 +8,78 @@ describe('debitAccountController', () => {
let req: Partial<Request>;
let res: Partial<Response>;

beforeAll(() => {
Account.startSession = jest.fn().mockReturnValue({
startTransaction: jest.fn(),
commitTransaction: jest.fn(),
abortTransaction: jest.fn(),
endSession: jest.fn(),
});
});

beforeEach(() => {
jest.clearAllMocks();
req = {
params: { accountId: '123' },
body: { cost: 300, date: '2025-04-02' },
params: { accountId: 'acc123' },
body: { cost: 200, date: '2025-04-02' },
};
res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
};
});

it('should debit the account and return 200', async () => {
const accountId = '123';
const debitCost = 300;
it('should debit the account and return the updated account and transaction', async () => {
const accountId = 'acc123';
const currentBalance = 1000;
const debitCost = 200;
const newBalance = currentBalance - debitCost;

const mockAccount = {
_id: accountId,
name: 'Test Account',
balance: currentBalance,
save: jest.fn().mockResolvedValueOnce({
_id: accountId,
name: 'Test Account',
balance: newBalance,
}),
};

Account.findById = jest.fn().mockResolvedValueOnce(mockAccount);
Transaction.create = jest.fn().mockResolvedValueOnce({
const mockTransaction = {
_id: 'txn123',
account: accountId,
type: TransactionType.debit,
cost: debitCost,
balance: newBalance,
description: 'Account debit',
});
};

Account.findById = jest.fn().mockReturnValueOnce({ session: jest.fn().mockResolvedValueOnce(mockAccount) });
Transaction.create = jest.fn().mockResolvedValueOnce(mockTransaction);

await debitAccountController(req as Request, res as Response);

expect(mockAccount.save).toHaveBeenCalled();
expect(Transaction.create).toHaveBeenCalledWith(
expect.objectContaining({
account: accountId,
type: TransactionType.debit,
cost: debitCost,
})
[
expect.objectContaining({
account: accountId,
type: TransactionType.debit,
cost: debitCost,
}),
],
expect.any(Object)
);
expect(res.status).toHaveBeenCalledWith(StatusCodes.CREATED);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
account: expect.objectContaining({
balance: newBalance,
}),
transaction: mockTransaction,
})
);
});

it('should return 404 if account is not found', async () => {
Account.findById = jest.fn().mockResolvedValueOnce(null);
Account.findById = jest.fn().mockReturnValueOnce({ session: jest.fn().mockResolvedValueOnce(null) });

await debitAccountController(req as Request, res as Response);

Expand All @@ -80,18 +92,15 @@ describe('debitAccountController', () => {
});

it('should return 400 if insufficient funds', async () => {
const accountId = '123';
const debitCost = 1500;
const currentBalance = 1000;
const accountId = 'acc123';
const currentBalance = 100;

const mockAccount = {
_id: accountId,
name: 'Test Account',
balance: currentBalance,
};

Account.findById = jest.fn().mockResolvedValueOnce(mockAccount);
req.body = { cost: debitCost };
Account.findById = jest.fn().mockReturnValueOnce({ session: jest.fn().mockResolvedValueOnce(mockAccount) });

await debitAccountController(req as Request, res as Response);

Expand All @@ -102,4 +111,12 @@ describe('debitAccountController', () => {
})
);
});

it('should handle errors and abort transaction', async () => {
Account.findById = jest
.fn()
.mockReturnValueOnce({ session: jest.fn().mockRejectedValueOnce(new Error('Database error')) });

await expect(debitAccountController(req as Request, res as Response)).rejects.toThrow('Database error');
});
});
Loading