Tests refactor
This commit is contained in:
parent
245520fb50
commit
99134d8556
165 changed files with 911 additions and 531 deletions
|
|
@ -0,0 +1,378 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { mockFind, mockSave, mockInsertMany, mockAggregate } = vi.hoisted(() => ({
|
||||
mockFind: vi.fn(),
|
||||
mockSave: vi.fn(),
|
||||
mockInsertMany: vi.fn(),
|
||||
mockAggregate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/schemas/cabinet-event.schema.js', () => {
|
||||
const chain = () => ({
|
||||
sort: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: mockFind,
|
||||
});
|
||||
|
||||
const aggChain = () => ({
|
||||
exec: mockAggregate,
|
||||
});
|
||||
|
||||
class FakeModel {
|
||||
data: unknown;
|
||||
constructor(data: unknown) {
|
||||
this.data = data;
|
||||
}
|
||||
save = mockSave;
|
||||
toObject() {
|
||||
return this.data;
|
||||
}
|
||||
static find = vi.fn(() => chain());
|
||||
static insertMany = mockInsertMany;
|
||||
static aggregate = vi.fn(() => aggChain());
|
||||
}
|
||||
|
||||
return { CabinetEventModel: FakeModel };
|
||||
});
|
||||
|
||||
import { CabinetEventsRepository } from '../../../src/modules/cabinet-events/cabinet-events.repository.js';
|
||||
|
||||
describe(CabinetEventsRepository.name, () => {
|
||||
let repo: CabinetEventsRepository;
|
||||
|
||||
const baseEventData = {
|
||||
householdId: 'hh1',
|
||||
userId: 'user-1',
|
||||
cabinetItemId: 'ci-1',
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
eventType: 'purchased' as const,
|
||||
quantity: 10,
|
||||
quantityBefore: 0,
|
||||
quantityAfter: 10,
|
||||
sourceType: 'manual' as const,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new CabinetEventsRepository();
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('creates and returns a cabinet event', async () => {
|
||||
mockSave.mockImplementation(function (this: { toObject: () => unknown }) {
|
||||
return Promise.resolve(this);
|
||||
});
|
||||
|
||||
const result = await repo.create(baseEventData);
|
||||
|
||||
expect(result).toEqual(baseEventData);
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('createMany', () => {
|
||||
it('inserts multiple events', async () => {
|
||||
const events = [baseEventData, { ...baseEventData, quantity: 5 }];
|
||||
mockInsertMany.mockResolvedValue(events);
|
||||
|
||||
const result = await repo.createMany(events);
|
||||
|
||||
expect(result).toEqual(events);
|
||||
expect(mockInsertMany).toHaveBeenCalledWith(events);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByHousehold', () => {
|
||||
it('returns paginated events with no filters', async () => {
|
||||
const items = [{ _id: 'ev-1', quantity: 10 }];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findByHousehold('hh1', { limit: 20 });
|
||||
|
||||
expect(result.data).toEqual(items);
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('handles cursor-based pagination', async () => {
|
||||
const items = [{ _id: 'ev-2', quantity: 5 }];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const cursor = Buffer.from('ev-1').toString('base64');
|
||||
const result = await repo.findByHousehold('hh1', { cursor, limit: 20 });
|
||||
|
||||
expect(result.data).toEqual(items);
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('sets hasMore when more items exist', async () => {
|
||||
const items = Array.from({ length: 3 }, (_, i) => ({ _id: `ev-${i}`, quantity: i }));
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findByHousehold('hh1', { limit: 2 });
|
||||
|
||||
expect(result.data).toHaveLength(2);
|
||||
expect(result.pagination.hasMore).toBe(true);
|
||||
expect(result.pagination.cursor).toBeTruthy();
|
||||
});
|
||||
|
||||
it('returns null cursor when no data', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
const result = await repo.findByHousehold('hh1', { limit: 20 });
|
||||
|
||||
expect(result.pagination.cursor).toBeNull();
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('filters by medicineId', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
await repo.findByHousehold('hh1', { medicineId: 'med-1', limit: 20 });
|
||||
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('filters by eventType', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
await repo.findByHousehold('hh1', { eventType: 'purchased' as never, limit: 20 });
|
||||
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('filters by startDate only', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
await repo.findByHousehold('hh1', {
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
limit: 20,
|
||||
});
|
||||
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('filters by endDate only', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
await repo.findByHousehold('hh1', {
|
||||
endDate: '2024-12-31T00:00:00.000Z',
|
||||
limit: 20,
|
||||
});
|
||||
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('filters by both startDate and endDate', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
await repo.findByHousehold('hh1', {
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-12-31T00:00:00.000Z',
|
||||
limit: 20,
|
||||
});
|
||||
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByCabinetItem', () => {
|
||||
it('returns paginated events for a cabinet item', async () => {
|
||||
const items = [{ _id: 'ev-1', cabinetItemId: 'ci-1' }];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findByCabinetItem('hh1', 'ci-1', { limit: 20 });
|
||||
|
||||
expect(result.data).toEqual(items);
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('handles cursor-based pagination', async () => {
|
||||
const items = [{ _id: 'ev-2' }];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const cursor = Buffer.from('ev-1').toString('base64');
|
||||
const result = await repo.findByCabinetItem('hh1', 'ci-1', { cursor, limit: 20 });
|
||||
|
||||
expect(result.data).toEqual(items);
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('sets hasMore when more items exist', async () => {
|
||||
const items = Array.from({ length: 3 }, (_, i) => ({ _id: `ev-${i}` }));
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findByCabinetItem('hh1', 'ci-1', { limit: 2 });
|
||||
|
||||
expect(result.data).toHaveLength(2);
|
||||
expect(result.pagination.hasMore).toBe(true);
|
||||
expect(result.pagination.cursor).toBeTruthy();
|
||||
});
|
||||
|
||||
it('returns null cursor when no data', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
const result = await repo.findByCabinetItem('hh1', 'ci-1', { limit: 20 });
|
||||
|
||||
expect(result.pagination.cursor).toBeNull();
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSpendingSummary', () => {
|
||||
it('returns spending summary with default month period', async () => {
|
||||
const byMedicine = [
|
||||
{
|
||||
_id: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
totalSpent: 100,
|
||||
totalQuantity: 10,
|
||||
avgUnitPrice: 10,
|
||||
purchaseCount: 2,
|
||||
currency: 'USD',
|
||||
},
|
||||
];
|
||||
const byPeriod = [{ _id: '2024-01', totalSpent: 100 }];
|
||||
|
||||
mockAggregate.mockResolvedValueOnce(byMedicine).mockResolvedValueOnce(byPeriod);
|
||||
|
||||
const result = await repo.getSpendingSummary('hh1', { period: 'month' });
|
||||
|
||||
expect(result.totalSpent).toBe(100);
|
||||
expect(result.currency).toBe('USD');
|
||||
expect(result.byMedicine).toHaveLength(1);
|
||||
expect(result.byMedicine[0].medicineId).toBe('med-1');
|
||||
expect(result.byMedicine[0].medicineName).toBe('Metformin');
|
||||
expect(result.byMedicine[0].totalSpent).toBe(100);
|
||||
expect(result.byMedicine[0].totalQuantity).toBe(10);
|
||||
expect(result.byMedicine[0].avgUnitPrice).toBe(10);
|
||||
expect(result.byMedicine[0].purchaseCount).toBe(2);
|
||||
expect(result.byPeriod).toHaveLength(1);
|
||||
expect(result.byPeriod[0].period).toBe('2024-01');
|
||||
expect(result.byPeriod[0].totalSpent).toBe(100);
|
||||
});
|
||||
|
||||
it('returns null currency when no medicine data', async () => {
|
||||
mockAggregate.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
|
||||
const result = await repo.getSpendingSummary('hh1', { period: 'month' });
|
||||
|
||||
expect(result.totalSpent).toBe(0);
|
||||
expect(result.currency).toBeNull();
|
||||
expect(result.byMedicine).toHaveLength(0);
|
||||
expect(result.byPeriod).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('filters by medicineId', async () => {
|
||||
mockAggregate.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
|
||||
await repo.getSpendingSummary('hh1', { period: 'month', medicineId: 'med-1' });
|
||||
|
||||
expect(mockAggregate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('filters by startDate only', async () => {
|
||||
mockAggregate.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
|
||||
await repo.getSpendingSummary('hh1', {
|
||||
period: 'month',
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
});
|
||||
|
||||
expect(mockAggregate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('filters by endDate only', async () => {
|
||||
mockAggregate.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
|
||||
await repo.getSpendingSummary('hh1', {
|
||||
period: 'month',
|
||||
endDate: '2024-12-31T00:00:00.000Z',
|
||||
});
|
||||
|
||||
expect(mockAggregate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('filters by both startDate and endDate', async () => {
|
||||
mockAggregate.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
|
||||
await repo.getSpendingSummary('hh1', {
|
||||
period: 'month',
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-12-31T00:00:00.000Z',
|
||||
});
|
||||
|
||||
expect(mockAggregate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('uses quarter date format', async () => {
|
||||
mockAggregate.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
|
||||
await repo.getSpendingSummary('hh1', { period: 'quarter' });
|
||||
|
||||
expect(mockAggregate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('uses year date format', async () => {
|
||||
mockAggregate.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
|
||||
await repo.getSpendingSummary('hh1', { period: 'year' });
|
||||
|
||||
expect(mockAggregate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('handles null currency in first medicine entry', async () => {
|
||||
const byMedicine = [
|
||||
{
|
||||
_id: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
totalSpent: 50,
|
||||
totalQuantity: 5,
|
||||
avgUnitPrice: 10,
|
||||
purchaseCount: 1,
|
||||
currency: null,
|
||||
},
|
||||
];
|
||||
mockAggregate.mockResolvedValueOnce(byMedicine).mockResolvedValueOnce([]);
|
||||
|
||||
const result = await repo.getSpendingSummary('hh1', { period: 'month' });
|
||||
|
||||
expect(result.currency).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAvgUnitPriceByMedicine', () => {
|
||||
it('returns empty map when no medicine ids provided', async () => {
|
||||
const result = await repo.getAvgUnitPriceByMedicine('hh1', []);
|
||||
|
||||
expect(result).toEqual(new Map());
|
||||
expect(mockAggregate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns map of avg unit prices', async () => {
|
||||
const results = [
|
||||
{ _id: 'med-1', avgUnitPrice: 10.5, currency: 'USD', totalSpent: 105, totalQuantity: 10 },
|
||||
{ _id: 'med-2', avgUnitPrice: 5.0, currency: 'EUR', totalSpent: 50, totalQuantity: 10 },
|
||||
];
|
||||
mockAggregate.mockResolvedValue(results);
|
||||
|
||||
const map = await repo.getAvgUnitPriceByMedicine('hh1', ['med-1', 'med-2']);
|
||||
|
||||
expect(map.size).toBe(2);
|
||||
expect(map.get('med-1')).toEqual({ avgUnitPrice: 10.5, currency: 'USD' });
|
||||
expect(map.get('med-2')).toEqual({ avgUnitPrice: 5.0, currency: 'EUR' });
|
||||
});
|
||||
|
||||
it('handles null currency in results', async () => {
|
||||
const results = [
|
||||
{ _id: 'med-1', avgUnitPrice: 10, currency: null, totalSpent: 100, totalQuantity: 10 },
|
||||
];
|
||||
mockAggregate.mockResolvedValue(results);
|
||||
|
||||
const map = await repo.getAvgUnitPriceByMedicine('hh1', ['med-1']);
|
||||
|
||||
expect(map.get('med-1')).toEqual({ avgUnitPrice: 10, currency: null });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,397 @@
|
|||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import Fastify from 'fastify';
|
||||
import { fastifyAwilixPlugin } from '@fastify/awilix';
|
||||
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
|
||||
|
||||
vi.mock('jose', () => ({
|
||||
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
|
||||
jwtVerify: vi.fn().mockResolvedValue({
|
||||
payload: {
|
||||
sub: 'kc-1',
|
||||
email: 'test@example.com',
|
||||
preferred_username: 'testuser',
|
||||
realm_access: { roles: ['member'] },
|
||||
householdIds: ['hh1'],
|
||||
},
|
||||
protectedHeader: { alg: 'RS256' },
|
||||
key: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
const { mockListEvents, mockGetEventsByItem, mockGetSpendingSummary } = vi.hoisted(() => ({
|
||||
mockListEvents: vi.fn(),
|
||||
mockGetEventsByItem: vi.fn(),
|
||||
mockGetSpendingSummary: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/cabinet-events/cabinet-events.repository.js', () => ({
|
||||
CabinetEventsRepository: class {
|
||||
create = vi.fn();
|
||||
createMany = vi.fn();
|
||||
findByHousehold = vi.fn();
|
||||
findByCabinetItem = vi.fn();
|
||||
getSpendingSummary = vi.fn();
|
||||
getAvgUnitPriceByMedicine = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/cabinet-events/cabinet-events.service.js', () => ({
|
||||
CabinetEventsService: class {
|
||||
logEvent = vi.fn();
|
||||
logEvents = vi.fn();
|
||||
listEvents = mockListEvents;
|
||||
getEventsByItem = mockGetEventsByItem;
|
||||
getSpendingSummary = mockGetSpendingSummary;
|
||||
getAvgUnitPrices = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/users/users.repository.js', () => ({
|
||||
UsersRepository: class {
|
||||
findByKeycloakId = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
|
||||
upsertFromToken = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
|
||||
},
|
||||
}));
|
||||
|
||||
import authPlugin from '../../../src/plugins/auth.plugin.js';
|
||||
import householdPlugin from '../../../src/plugins/household.plugin.js';
|
||||
import usersRoutes from '../../../src/modules/users/users.routes.js';
|
||||
import cabinetEventsRoutes from '../../../src/modules/cabinet-events/cabinet-events.routes.js';
|
||||
|
||||
function makeFakeEvent(overrides = {}) {
|
||||
return {
|
||||
_id: 'ev-1',
|
||||
householdId: 'hh1',
|
||||
userId: 'kc-1',
|
||||
cabinetItemId: 'ci-1',
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
eventType: 'purchased',
|
||||
quantity: 10,
|
||||
quantityBefore: 0,
|
||||
quantityAfter: 10,
|
||||
sourceType: 'manual',
|
||||
createdAt: '2024-06-01T00:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('cabinet-events.routes', () => {
|
||||
let app: Awaited<ReturnType<typeof buildTestApp>>;
|
||||
|
||||
async function buildTestApp() {
|
||||
const instance = Fastify({ logger: false });
|
||||
instance.setValidatorCompiler(validatorCompiler);
|
||||
instance.setSerializerCompiler(serializerCompiler);
|
||||
await instance.register(fastifyAwilixPlugin, {
|
||||
disposeOnClose: true,
|
||||
disposeOnResponse: true,
|
||||
strictBooleanEnforced: true,
|
||||
});
|
||||
await instance.register(authPlugin);
|
||||
await instance.register(householdPlugin);
|
||||
await instance.register(usersRoutes);
|
||||
await instance.register(cabinetEventsRoutes);
|
||||
await instance.ready();
|
||||
return instance;
|
||||
}
|
||||
|
||||
const authHeaders = { authorization: 'Bearer valid-token' };
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
app = await buildTestApp();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/cabinet-events', () => {
|
||||
it('returns paginated event list', async () => {
|
||||
const event = makeFakeEvent();
|
||||
mockListEvents.mockResolvedValue({
|
||||
data: [event],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet-events',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].medicineName).toBe('Metformin');
|
||||
expect(body.data[0].eventType).toBe('purchased');
|
||||
expect(body.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('handles ObjectId and Date objects in response', async () => {
|
||||
const event = makeFakeEvent({
|
||||
_id: { toString: () => 'ev-obj' },
|
||||
createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
|
||||
unitPrice: 5.5,
|
||||
totalPrice: 55,
|
||||
currency: 'USD',
|
||||
storeId: 'store-1',
|
||||
storeName: 'Pharmacy A',
|
||||
sourceId: 'src-1',
|
||||
reason: 'restocking',
|
||||
notes: 'bulk purchase',
|
||||
});
|
||||
mockListEvents.mockResolvedValue({
|
||||
data: [event],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet-events',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0]._id).toBe('ev-obj');
|
||||
expect(body.data[0].createdAt).toBe('2024-01-01T00:00:00.000Z');
|
||||
expect(body.data[0].unitPrice).toBe(5.5);
|
||||
expect(body.data[0].totalPrice).toBe(55);
|
||||
expect(body.data[0].currency).toBe('USD');
|
||||
expect(body.data[0].storeId).toBe('store-1');
|
||||
expect(body.data[0].storeName).toBe('Pharmacy A');
|
||||
expect(body.data[0].sourceId).toBe('src-1');
|
||||
expect(body.data[0].reason).toBe('restocking');
|
||||
expect(body.data[0].notes).toBe('bulk purchase');
|
||||
});
|
||||
|
||||
it('handles Date instances in createdAt', async () => {
|
||||
const event = makeFakeEvent({
|
||||
createdAt: new Date('2024-03-15T12:00:00.000Z'),
|
||||
});
|
||||
mockListEvents.mockResolvedValue({
|
||||
data: [event],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet-events',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0].createdAt).toBe('2024-03-15T12:00:00.000Z');
|
||||
});
|
||||
|
||||
it('omits null optional fields from response', async () => {
|
||||
const event = makeFakeEvent({
|
||||
unitPrice: null,
|
||||
totalPrice: null,
|
||||
currency: null,
|
||||
storeId: null,
|
||||
storeName: null,
|
||||
sourceId: null,
|
||||
reason: null,
|
||||
notes: null,
|
||||
});
|
||||
mockListEvents.mockResolvedValue({
|
||||
data: [event],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet-events',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0].unitPrice).toBeUndefined();
|
||||
expect(body.data[0].totalPrice).toBeUndefined();
|
||||
expect(body.data[0].currency).toBeUndefined();
|
||||
expect(body.data[0].storeId).toBeUndefined();
|
||||
expect(body.data[0].storeName).toBeUndefined();
|
||||
expect(body.data[0].sourceId).toBeUndefined();
|
||||
expect(body.data[0].reason).toBeUndefined();
|
||||
expect(body.data[0].notes).toBeUndefined();
|
||||
});
|
||||
|
||||
it('passes query parameters to service', async () => {
|
||||
mockListEvents.mockResolvedValue({
|
||||
data: [],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet-events?medicineId=med-1&eventType=purchased&limit=10',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(mockListEvents).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
expect.objectContaining({
|
||||
medicineId: 'med-1',
|
||||
eventType: 'purchased',
|
||||
limit: 10,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/cabinet-events/by-item/:cabinetItemId', () => {
|
||||
it('returns paginated events for a cabinet item', async () => {
|
||||
const event = makeFakeEvent();
|
||||
mockGetEventsByItem.mockResolvedValue({
|
||||
data: [event],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet-events/by-item/ci-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].cabinetItemId).toBe('ci-1');
|
||||
expect(body.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('passes query parameters to service', async () => {
|
||||
mockGetEventsByItem.mockResolvedValue({
|
||||
data: [],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet-events/by-item/ci-1?limit=5&cursor=abc',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(mockGetEventsByItem).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
'ci-1',
|
||||
expect.objectContaining({
|
||||
limit: 5,
|
||||
cursor: 'abc',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('handles ObjectId and Date objects in by-item response', async () => {
|
||||
const event = makeFakeEvent({
|
||||
_id: { toString: () => 'ev-obj-2' },
|
||||
createdAt: new Date('2024-05-01T00:00:00.000Z'),
|
||||
});
|
||||
mockGetEventsByItem.mockResolvedValue({
|
||||
data: [event],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet-events/by-item/ci-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0]._id).toBe('ev-obj-2');
|
||||
expect(body.data[0].createdAt).toBe('2024-05-01T00:00:00.000Z');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/cabinet-events/spending-summary', () => {
|
||||
it('returns spending summary', async () => {
|
||||
mockGetSpendingSummary.mockResolvedValue({
|
||||
totalSpent: 250,
|
||||
currency: 'USD',
|
||||
byMedicine: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
totalSpent: 250,
|
||||
totalQuantity: 25,
|
||||
avgUnitPrice: 10,
|
||||
purchaseCount: 5,
|
||||
},
|
||||
],
|
||||
byPeriod: [
|
||||
{ period: '2024-01', totalSpent: 100 },
|
||||
{ period: '2024-02', totalSpent: 150 },
|
||||
],
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet-events/spending-summary',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.totalSpent).toBe(250);
|
||||
expect(body.currency).toBe('USD');
|
||||
expect(body.byMedicine).toHaveLength(1);
|
||||
expect(body.byMedicine[0].medicineId).toBe('med-1');
|
||||
expect(body.byPeriod).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('passes query parameters to service', async () => {
|
||||
mockGetSpendingSummary.mockResolvedValue({
|
||||
totalSpent: 0,
|
||||
currency: null,
|
||||
byMedicine: [],
|
||||
byPeriod: [],
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet-events/spending-summary?period=quarter&medicineId=med-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(mockGetSpendingSummary).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
expect.objectContaining({
|
||||
period: 'quarter',
|
||||
medicineId: 'med-1',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('returns empty summary with null currency', async () => {
|
||||
mockGetSpendingSummary.mockResolvedValue({
|
||||
totalSpent: 0,
|
||||
currency: null,
|
||||
byMedicine: [],
|
||||
byPeriod: [],
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/cabinet-events/spending-summary',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.totalSpent).toBe(0);
|
||||
expect(body.currency).toBeNull();
|
||||
expect(body.byMedicine).toHaveLength(0);
|
||||
expect(body.byPeriod).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,144 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { CabinetEventsService } from '../../../src/modules/cabinet-events/cabinet-events.service.js';
|
||||
|
||||
describe(CabinetEventsService.name, () => {
|
||||
const mockCabinetEventsRepo = {
|
||||
create: vi.fn(),
|
||||
createMany: vi.fn(),
|
||||
findByHousehold: vi.fn(),
|
||||
findByCabinetItem: vi.fn(),
|
||||
getSpendingSummary: vi.fn(),
|
||||
getAvgUnitPriceByMedicine: vi.fn(),
|
||||
};
|
||||
|
||||
let service: CabinetEventsService;
|
||||
|
||||
const baseEventData = {
|
||||
householdId: 'hh1',
|
||||
userId: 'user-1',
|
||||
cabinetItemId: 'ci-1',
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Metformin',
|
||||
eventType: 'purchased' as const,
|
||||
quantity: 10,
|
||||
quantityBefore: 0,
|
||||
quantityAfter: 10,
|
||||
sourceType: 'manual' as const,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new CabinetEventsService({
|
||||
cabinetEventsRepository: mockCabinetEventsRepo as never,
|
||||
});
|
||||
});
|
||||
|
||||
describe('logEvent', () => {
|
||||
it('delegates to repository create', async () => {
|
||||
const created = { _id: 'ev-1', ...baseEventData };
|
||||
mockCabinetEventsRepo.create.mockResolvedValue(created);
|
||||
|
||||
const result = await service.logEvent(baseEventData);
|
||||
|
||||
expect(result).toEqual(created);
|
||||
expect(mockCabinetEventsRepo.create).toHaveBeenCalledWith(baseEventData);
|
||||
});
|
||||
});
|
||||
|
||||
describe('logEvents', () => {
|
||||
it('delegates to repository createMany', async () => {
|
||||
const events = [baseEventData, { ...baseEventData, quantity: 5 }];
|
||||
const inserted = events.map((e, i) => ({ _id: `ev-${i}`, ...e }));
|
||||
mockCabinetEventsRepo.createMany.mockResolvedValue(inserted);
|
||||
|
||||
const result = await service.logEvents(events);
|
||||
|
||||
expect(result).toEqual(inserted);
|
||||
expect(mockCabinetEventsRepo.createMany).toHaveBeenCalledWith(events);
|
||||
});
|
||||
|
||||
it('returns empty array for empty input without calling repository', async () => {
|
||||
const result = await service.logEvents([]);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
expect(mockCabinetEventsRepo.createMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('listEvents', () => {
|
||||
it('delegates to repository findByHousehold', async () => {
|
||||
const expected = {
|
||||
data: [{ _id: 'ev-1' }],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
};
|
||||
mockCabinetEventsRepo.findByHousehold.mockResolvedValue(expected);
|
||||
|
||||
const query = { limit: 20 };
|
||||
const result = await service.listEvents('hh1', query);
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
expect(mockCabinetEventsRepo.findByHousehold).toHaveBeenCalledWith('hh1', query);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getEventsByItem', () => {
|
||||
it('delegates to repository findByCabinetItem', async () => {
|
||||
const expected = {
|
||||
data: [{ _id: 'ev-1', cabinetItemId: 'ci-1' }],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
};
|
||||
mockCabinetEventsRepo.findByCabinetItem.mockResolvedValue(expected);
|
||||
|
||||
const query = { limit: 20 };
|
||||
const result = await service.getEventsByItem('hh1', 'ci-1', query);
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
expect(mockCabinetEventsRepo.findByCabinetItem).toHaveBeenCalledWith('hh1', 'ci-1', query);
|
||||
});
|
||||
|
||||
it('passes cursor through to repository', async () => {
|
||||
const expected = {
|
||||
data: [],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
};
|
||||
mockCabinetEventsRepo.findByCabinetItem.mockResolvedValue(expected);
|
||||
|
||||
const query = { cursor: 'abc123', limit: 10 };
|
||||
await service.getEventsByItem('hh1', 'ci-1', query);
|
||||
|
||||
expect(mockCabinetEventsRepo.findByCabinetItem).toHaveBeenCalledWith('hh1', 'ci-1', query);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSpendingSummary', () => {
|
||||
it('delegates to repository getSpendingSummary', async () => {
|
||||
const expected = {
|
||||
totalSpent: 100,
|
||||
currency: 'USD',
|
||||
byMedicine: [],
|
||||
byPeriod: [],
|
||||
};
|
||||
mockCabinetEventsRepo.getSpendingSummary.mockResolvedValue(expected);
|
||||
|
||||
const query = { period: 'month' as const };
|
||||
const result = await service.getSpendingSummary('hh1', query);
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
expect(mockCabinetEventsRepo.getSpendingSummary).toHaveBeenCalledWith('hh1', query);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAvgUnitPrices', () => {
|
||||
it('delegates to repository getAvgUnitPriceByMedicine', async () => {
|
||||
const expected = new Map([['med-1', { avgUnitPrice: 10, currency: 'USD' }]]);
|
||||
mockCabinetEventsRepo.getAvgUnitPriceByMedicine.mockResolvedValue(expected);
|
||||
|
||||
const result = await service.getAvgUnitPrices('hh1', ['med-1']);
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
expect(mockCabinetEventsRepo.getAvgUnitPriceByMedicine).toHaveBeenCalledWith('hh1', [
|
||||
'med-1',
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue