Tests refactor
This commit is contained in:
parent
245520fb50
commit
99134d8556
165 changed files with 911 additions and 531 deletions
207
packages/api/tests/modules/refills/refills.repository.test.ts
Normal file
207
packages/api/tests/modules/refills/refills.repository.test.ts
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { mockFind, mockFindOne, mockFindOneAndUpdate, mockSave } = vi.hoisted(() => ({
|
||||
mockFind: vi.fn(),
|
||||
mockFindOne: vi.fn(),
|
||||
mockFindOneAndUpdate: vi.fn(),
|
||||
mockSave: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/schemas/refill-list.schema.js', () => {
|
||||
const chain = () => ({
|
||||
sort: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: mockFind,
|
||||
});
|
||||
const findOneChain = () => ({ lean: vi.fn().mockReturnThis(), exec: mockFindOne });
|
||||
const updateChain = () => ({ exec: mockFindOneAndUpdate });
|
||||
|
||||
class FakeModel {
|
||||
data: unknown;
|
||||
constructor(data: unknown) {
|
||||
this.data = data;
|
||||
}
|
||||
save = mockSave;
|
||||
toObject() {
|
||||
return this.data;
|
||||
}
|
||||
static find = vi.fn(() => chain());
|
||||
static findOne = vi.fn(() => findOneChain());
|
||||
static findOneAndUpdate = vi.fn(() => updateChain());
|
||||
}
|
||||
return { RefillListModel: FakeModel };
|
||||
});
|
||||
|
||||
import { RefillsRepository } from '../../../src/modules/refills/refills.repository.js';
|
||||
|
||||
describe(RefillsRepository.name, () => {
|
||||
let repo: RefillsRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new RefillsRepository();
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('saves and returns refill list', async () => {
|
||||
const data = {
|
||||
householdId: 'hh1',
|
||||
name: 'Monthly Refills',
|
||||
status: 'active',
|
||||
createdBy: 'user-1',
|
||||
items: [],
|
||||
};
|
||||
mockSave.mockImplementation(function (this: { toObject: () => unknown }) {
|
||||
return Promise.resolve(this);
|
||||
});
|
||||
|
||||
const result = await repo.create(data);
|
||||
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
expect(result).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByHousehold', () => {
|
||||
it('returns paginated lists', async () => {
|
||||
const lists = [{ _id: 'rl-1', name: 'Monthly Refills' }];
|
||||
mockFind.mockResolvedValue(lists);
|
||||
|
||||
const result = await repo.findByHousehold('hh1', { limit: 20 });
|
||||
|
||||
expect(result.data).toEqual(lists);
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
expect(result.pagination.cursor).toBeNull();
|
||||
});
|
||||
|
||||
it('sets hasMore when more lists exist', async () => {
|
||||
const lists = [{ _id: 'rl-1' }, { _id: 'rl-2' }, { _id: 'rl-3' }];
|
||||
mockFind.mockResolvedValue(lists);
|
||||
|
||||
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('handles cursor pagination', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
const cursor = Buffer.from('rl-1').toString('base64');
|
||||
const result = await repo.findByHousehold('hh1', { cursor, limit: 20 });
|
||||
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('filters by status', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
await repo.findByHousehold('hh1', { status: 'active' as never, limit: 20 });
|
||||
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns null cursor when no data', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
|
||||
const result = await repo.findByHousehold('hh1', { limit: 20 });
|
||||
|
||||
expect(result.pagination.cursor).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('returns list when found', async () => {
|
||||
const list = { _id: 'rl-1', name: 'Monthly Refills' };
|
||||
mockFindOne.mockResolvedValue(list);
|
||||
|
||||
const result = await repo.findById('rl-1', 'hh1');
|
||||
|
||||
expect(result).toEqual(list);
|
||||
});
|
||||
|
||||
it('returns null when not found', async () => {
|
||||
mockFindOne.mockResolvedValue(null);
|
||||
|
||||
expect(await repo.findById('missing', 'hh1')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('updates and returns list', async () => {
|
||||
const updated = { _id: 'rl-1', name: 'Updated' };
|
||||
mockFindOneAndUpdate.mockResolvedValue(updated);
|
||||
|
||||
const result = await repo.update('rl-1', 'hh1', { name: 'Updated' });
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
|
||||
it('updates status field', async () => {
|
||||
mockFindOneAndUpdate.mockResolvedValue({ _id: 'rl-1', status: 'shopping' });
|
||||
|
||||
const result = await repo.update('rl-1', 'hh1', { status: 'shopping' as never });
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
});
|
||||
|
||||
it('updates preferredStoreId field', async () => {
|
||||
mockFindOneAndUpdate.mockResolvedValue({ _id: 'rl-1', preferredStoreId: 'st-1' });
|
||||
|
||||
const result = await repo.update('rl-1', 'hh1', { preferredStoreId: 'st-1' });
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
});
|
||||
|
||||
it('returns null when not found', async () => {
|
||||
mockFindOneAndUpdate.mockResolvedValue(null);
|
||||
|
||||
expect(await repo.update('missing', 'hh1', {})).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateItem', () => {
|
||||
it('updates item and returns list', async () => {
|
||||
const updated = { _id: 'rl-1', items: [{ _id: 'item-1', checked: true }] };
|
||||
mockFindOneAndUpdate.mockResolvedValue(updated);
|
||||
|
||||
const result = await repo.updateItem('rl-1', 'hh1', 'item-1', { checked: true });
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
|
||||
it('updates actualPrice, storeId, and notes', async () => {
|
||||
mockFindOneAndUpdate.mockResolvedValue({ _id: 'rl-1', items: [] });
|
||||
|
||||
await repo.updateItem('rl-1', 'hh1', 'item-1', {
|
||||
actualPrice: 9.99,
|
||||
storeId: 'st-1',
|
||||
notes: 'picked up at CVS',
|
||||
});
|
||||
|
||||
expect(mockFindOneAndUpdate).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('includes checkedAt when provided', async () => {
|
||||
mockFindOneAndUpdate.mockResolvedValue({ _id: 'rl-1', items: [] });
|
||||
|
||||
const checkedAt = new Date();
|
||||
await repo.updateItem('rl-1', 'hh1', 'item-1', { checked: true, checkedAt });
|
||||
|
||||
expect(mockFindOneAndUpdate).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('markItemsAddedToCabinet', () => {
|
||||
it('marks items and returns list', async () => {
|
||||
const updated = { _id: 'rl-1', items: [] };
|
||||
mockFindOneAndUpdate.mockResolvedValue(updated);
|
||||
|
||||
const result = await repo.markItemsAddedToCabinet('rl-1', 'hh1', ['item-1', 'item-2']);
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
});
|
||||
});
|
||||
522
packages/api/tests/modules/refills/refills.routes.test.ts
Normal file
522
packages/api/tests/modules/refills/refills.routes.test.ts
Normal file
|
|
@ -0,0 +1,522 @@
|
|||
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 {
|
||||
mockGetAlerts,
|
||||
mockCreateList,
|
||||
mockList,
|
||||
mockGetById,
|
||||
mockUpdateList,
|
||||
mockUpdateItem,
|
||||
mockAddToCabinet,
|
||||
mockGetStoreComparison,
|
||||
} = vi.hoisted(() => ({
|
||||
mockGetAlerts: vi.fn(),
|
||||
mockCreateList: vi.fn(),
|
||||
mockList: vi.fn(),
|
||||
mockGetById: vi.fn(),
|
||||
mockUpdateList: vi.fn(),
|
||||
mockUpdateItem: vi.fn(),
|
||||
mockAddToCabinet: vi.fn(),
|
||||
mockGetStoreComparison: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/refills/refills.repository.js', () => ({
|
||||
RefillsRepository: class {
|
||||
create = vi.fn();
|
||||
findByHousehold = vi.fn();
|
||||
findById = vi.fn();
|
||||
update = vi.fn();
|
||||
updateItem = vi.fn();
|
||||
markItemsAddedToCabinet = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/refills/refills.service.js', () => ({
|
||||
RefillsService: class {
|
||||
getAlerts = mockGetAlerts;
|
||||
createList = mockCreateList;
|
||||
list = mockList;
|
||||
getById = mockGetById;
|
||||
updateList = mockUpdateList;
|
||||
updateItem = mockUpdateItem;
|
||||
addToCabinet = mockAddToCabinet;
|
||||
getStoreComparison = mockGetStoreComparison;
|
||||
},
|
||||
}));
|
||||
|
||||
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 refillsRoutes from '../../../src/modules/refills/refills.routes.js';
|
||||
|
||||
function makeFakeRefillList(overrides = {}) {
|
||||
return {
|
||||
_id: 'rl-1',
|
||||
householdId: 'hh1',
|
||||
name: 'Monthly Refills',
|
||||
items: [],
|
||||
status: 'active',
|
||||
createdBy: 'kc-1',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('refills.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(refillsRoutes);
|
||||
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/refills/alerts', () => {
|
||||
it('returns alerts with price options', async () => {
|
||||
mockGetAlerts.mockResolvedValue([
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
medicineStrength: 500,
|
||||
medicineStrengthUnit: 'mg',
|
||||
daysUntilEmpty: 3,
|
||||
dailyConsumption: 2,
|
||||
currentStock: 6,
|
||||
suggestedQuantity: 60,
|
||||
lastKnownPrice: {
|
||||
price: 10,
|
||||
pricePerUnit: 0.1,
|
||||
storeName: 'CVS',
|
||||
storeId: 'st-1',
|
||||
date: new Date('2026-01-01T00:00:00.000Z'),
|
||||
},
|
||||
cheapestOption: {
|
||||
price: 8,
|
||||
pricePerUnit: 0.08,
|
||||
storeName: 'Walmart',
|
||||
storeId: 'st-2',
|
||||
date: new Date('2026-01-02T00:00:00.000Z'),
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/refills/alerts',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0].lastKnownPrice.storeName).toBe('CVS');
|
||||
expect(body.data[0].lastKnownPrice.date).toBe('2026-01-01T00:00:00.000Z');
|
||||
expect(body.data[0].cheapestOption.storeName).toBe('Walmart');
|
||||
});
|
||||
|
||||
it('returns alerts', async () => {
|
||||
mockGetAlerts.mockResolvedValue([
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
medicineStrength: 500,
|
||||
medicineStrengthUnit: 'mg',
|
||||
daysUntilEmpty: 3,
|
||||
dailyConsumption: 2,
|
||||
currentStock: 6,
|
||||
suggestedQuantity: 60,
|
||||
},
|
||||
]);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/refills/alerts',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].medicineName).toBe('Aspirin');
|
||||
});
|
||||
|
||||
it('uses requesting user by default', async () => {
|
||||
mockGetAlerts.mockResolvedValue([]);
|
||||
|
||||
await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/refills/alerts',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(mockGetAlerts).toHaveBeenCalledWith('hh1', 'kc-1', 7);
|
||||
});
|
||||
|
||||
it('uses userId query param when provided', async () => {
|
||||
mockGetAlerts.mockResolvedValue([]);
|
||||
|
||||
await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/refills/alerts?userId=other-user&thresholdDays=14',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(mockGetAlerts).toHaveBeenCalledWith('hh1', 'other-user', 14);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/refills/lists', () => {
|
||||
it('creates list and returns 201', async () => {
|
||||
mockCreateList.mockResolvedValue(makeFakeRefillList());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/refills/lists',
|
||||
headers: authHeaders,
|
||||
payload: { name: 'Monthly Refills', fromAlerts: false, thresholdDays: 7 },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(res.json().name).toBe('Monthly Refills');
|
||||
});
|
||||
|
||||
it('passes householdId and userId to service', async () => {
|
||||
mockCreateList.mockResolvedValue(makeFakeRefillList());
|
||||
|
||||
await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/refills/lists',
|
||||
headers: authHeaders,
|
||||
payload: { name: 'Auto List', fromAlerts: true, thresholdDays: 7 },
|
||||
});
|
||||
|
||||
expect(mockCreateList).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 'Auto List', fromAlerts: true }),
|
||||
'hh1',
|
||||
'kc-1',
|
||||
);
|
||||
});
|
||||
|
||||
it('returns 400 for missing name', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/refills/lists',
|
||||
headers: authHeaders,
|
||||
payload: {},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/refills/lists', () => {
|
||||
it('returns paginated lists', async () => {
|
||||
mockList.mockResolvedValue({
|
||||
data: [makeFakeRefillList()],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/refills/lists',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('includes optional list fields in response', async () => {
|
||||
mockList.mockResolvedValue({
|
||||
data: [
|
||||
makeFakeRefillList({
|
||||
preferredStoreId: 'st-1',
|
||||
totalEstimatedCost: 25.5,
|
||||
items: [
|
||||
{
|
||||
_id: 'item-1',
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
quantity: 30,
|
||||
unit: 'tablet',
|
||||
estimatedPrice: 10,
|
||||
actualPrice: 9.5,
|
||||
checked: true,
|
||||
checkedAt: new Date('2026-01-10T00:00:00.000Z'),
|
||||
addedToCabinet: false,
|
||||
storeId: 'st-1',
|
||||
notes: 'generic brand',
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/refills/lists',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0].preferredStoreId).toBe('st-1');
|
||||
expect(body.data[0].totalEstimatedCost).toBe(25.5);
|
||||
const item = body.data[0].items[0];
|
||||
expect(item.estimatedPrice).toBe(10);
|
||||
expect(item.actualPrice).toBe(9.5);
|
||||
expect(item.checkedAt).toBe('2026-01-10T00:00:00.000Z');
|
||||
expect(item.storeId).toBe('st-1');
|
||||
expect(item.notes).toBe('generic brand');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/refills/lists/:id', () => {
|
||||
it('returns single list', async () => {
|
||||
mockGetById.mockResolvedValue(makeFakeRefillList());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/refills/lists/rl-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().name).toBe('Monthly Refills');
|
||||
});
|
||||
|
||||
it('handles ObjectId-style _id in list and items', async () => {
|
||||
mockGetById.mockResolvedValue(
|
||||
makeFakeRefillList({
|
||||
_id: { toString: () => 'rl-obj' },
|
||||
createdAt: new Date('2026-01-01T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-01-01T00:00:00.000Z'),
|
||||
items: [
|
||||
{
|
||||
_id: { toString: () => 'item-obj' },
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
quantity: 30,
|
||||
unit: 'tablet',
|
||||
checked: false,
|
||||
addedToCabinet: false,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/refills/lists/rl-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body._id).toBe('rl-obj');
|
||||
expect(body.items[0]._id).toBe('item-obj');
|
||||
expect(body.createdAt).toBe('2026-01-01T00:00:00.000Z');
|
||||
});
|
||||
|
||||
it('passes id and householdId to service', async () => {
|
||||
mockGetById.mockResolvedValue(makeFakeRefillList());
|
||||
|
||||
await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/refills/lists/rl-99',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(mockGetById).toHaveBeenCalledWith('rl-99', 'hh1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/households/:householdId/refills/lists/:id', () => {
|
||||
it('updates list and returns 200', async () => {
|
||||
mockUpdateList.mockResolvedValue(makeFakeRefillList({ name: 'Updated' }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/refills/lists/rl-1',
|
||||
headers: authHeaders,
|
||||
payload: { name: 'Updated' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().name).toBe('Updated');
|
||||
});
|
||||
|
||||
it('passes id, householdId, body to service', async () => {
|
||||
mockUpdateList.mockResolvedValue(makeFakeRefillList());
|
||||
|
||||
await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/refills/lists/rl-1',
|
||||
headers: authHeaders,
|
||||
payload: { status: 'shopping' },
|
||||
});
|
||||
|
||||
expect(mockUpdateList).toHaveBeenCalledWith(
|
||||
'rl-1',
|
||||
'hh1',
|
||||
expect.objectContaining({ status: 'shopping' }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/households/:householdId/refills/lists/:id/items/:itemId', () => {
|
||||
it('updates item and returns 200', async () => {
|
||||
mockUpdateItem.mockResolvedValue(makeFakeRefillList());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/refills/lists/rl-1/items/item-1',
|
||||
headers: authHeaders,
|
||||
payload: { checked: true },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('passes listId, householdId, itemId, body to service', async () => {
|
||||
mockUpdateItem.mockResolvedValue(makeFakeRefillList());
|
||||
|
||||
await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/refills/lists/rl-1/items/item-99',
|
||||
headers: authHeaders,
|
||||
payload: { actualPrice: 9.99 },
|
||||
});
|
||||
|
||||
expect(mockUpdateItem).toHaveBeenCalledWith(
|
||||
'rl-1',
|
||||
'hh1',
|
||||
'item-99',
|
||||
expect.objectContaining({ actualPrice: 9.99 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/refills/lists/:id/add-to-cabinet', () => {
|
||||
it('adds items to cabinet and returns summary', async () => {
|
||||
mockAddToCabinet.mockResolvedValue({ addedCount: 2, priceRecordsCreated: 0 });
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/refills/lists/rl-1/add-to-cabinet',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.addedCount).toBe(2);
|
||||
expect(body.priceRecordsCreated).toBe(0);
|
||||
});
|
||||
|
||||
it('passes listId, householdId, userId to service', async () => {
|
||||
mockAddToCabinet.mockResolvedValue({ addedCount: 0, priceRecordsCreated: 0 });
|
||||
|
||||
await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/refills/lists/rl-1/add-to-cabinet',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(mockAddToCabinet).toHaveBeenCalledWith('rl-1', 'hh1', 'kc-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/refills/lists/:id/store-comparison', () => {
|
||||
it('returns store comparison data', async () => {
|
||||
mockGetStoreComparison.mockResolvedValue([
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
storeOptions: [
|
||||
{
|
||||
storeId: 'st-1',
|
||||
storeName: 'CVS',
|
||||
latestPrice: 8,
|
||||
latestPricePerUnit: 0.08,
|
||||
currency: 'USD',
|
||||
date: new Date('2026-01-01T00:00:00.000Z'),
|
||||
isInsurancePrice: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/refills/lists/rl-1/store-comparison',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].storeOptions[0].date).toBe('2026-01-01T00:00:00.000Z');
|
||||
});
|
||||
|
||||
it('passes listId and householdId to service', async () => {
|
||||
mockGetStoreComparison.mockResolvedValue([]);
|
||||
|
||||
await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/refills/lists/rl-99/store-comparison',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(mockGetStoreComparison).toHaveBeenCalledWith('rl-99', 'hh1');
|
||||
});
|
||||
});
|
||||
});
|
||||
506
packages/api/tests/modules/refills/refills.service.test.ts
Normal file
506
packages/api/tests/modules/refills/refills.service.test.ts
Normal file
|
|
@ -0,0 +1,506 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { RefillsService } from '../../../src/modules/refills/refills.service.js';
|
||||
|
||||
describe(RefillsService.name, () => {
|
||||
const mockRepo = {
|
||||
create: vi.fn(),
|
||||
findByHousehold: vi.fn(),
|
||||
findById: vi.fn(),
|
||||
update: vi.fn(),
|
||||
updateItem: vi.fn(),
|
||||
markItemsAddedToCabinet: vi.fn(),
|
||||
};
|
||||
const mockRegimensService = {
|
||||
calculateBurnRates: vi.fn(),
|
||||
};
|
||||
const mockCabinetRepo = {
|
||||
getAggregateSummary: vi.fn(),
|
||||
};
|
||||
const mockCabinetService = {
|
||||
addItem: vi.fn(),
|
||||
};
|
||||
const mockPricesRepo = {
|
||||
getLatestForMedicine: vi.fn(),
|
||||
compareStores: vi.fn(),
|
||||
};
|
||||
const mockPurchasesRepo = {
|
||||
getPendingMedicineStock: vi.fn(),
|
||||
};
|
||||
|
||||
let service: RefillsService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockPurchasesRepo.getPendingMedicineStock.mockResolvedValue([]);
|
||||
service = new RefillsService({
|
||||
refillsRepository: mockRepo as never,
|
||||
regimensService: mockRegimensService as never,
|
||||
cabinetRepository: mockCabinetRepo as never,
|
||||
cabinetService: mockCabinetService as never,
|
||||
medicinePricesRepository: mockPricesRepo as never,
|
||||
purchasesRepository: mockPurchasesRepo as never,
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAlerts', () => {
|
||||
it('returns empty array when no medicines are running low', async () => {
|
||||
mockRegimensService.calculateBurnRates.mockResolvedValue([
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
dailyConsumption: 1,
|
||||
totalInCabinet: 100,
|
||||
daysUntilEmpty: 100,
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await service.getAlerts('hh1', 'user-1', 7);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns alerts for medicines below threshold', async () => {
|
||||
mockRegimensService.calculateBurnRates.mockResolvedValue([
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
dailyConsumption: 2,
|
||||
totalInCabinet: 10,
|
||||
daysUntilEmpty: 5,
|
||||
},
|
||||
]);
|
||||
mockCabinetRepo.getAggregateSummary.mockResolvedValue([
|
||||
{ _id: 'med-1', medicineStrength: 500, medicineStrengthUnit: 'mg' },
|
||||
]);
|
||||
mockPricesRepo.getLatestForMedicine.mockResolvedValue(null);
|
||||
mockPricesRepo.compareStores.mockResolvedValue([]);
|
||||
|
||||
const result = await service.getAlerts('hh1', 'user-1', 7);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].medicineId).toBe('med-1');
|
||||
expect(result[0].daysUntilEmpty).toBe(5);
|
||||
expect(result[0].suggestedQuantity).toBe(60); // ceil(2 * 30)
|
||||
});
|
||||
|
||||
it('attaches lastKnownPrice when available', async () => {
|
||||
mockRegimensService.calculateBurnRates.mockResolvedValue([
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
dailyConsumption: 2,
|
||||
totalInCabinet: 5,
|
||||
daysUntilEmpty: 2,
|
||||
},
|
||||
]);
|
||||
mockCabinetRepo.getAggregateSummary.mockResolvedValue([]);
|
||||
mockPricesRepo.getLatestForMedicine.mockResolvedValue({
|
||||
price: 10,
|
||||
pricePerUnit: 0.1,
|
||||
storeName: 'Walgreens',
|
||||
storeId: 'st-1',
|
||||
date: new Date('2026-01-01T00:00:00.000Z'),
|
||||
});
|
||||
mockPricesRepo.compareStores.mockResolvedValue([]);
|
||||
|
||||
const result = await service.getAlerts('hh1', 'user-1', 7);
|
||||
|
||||
expect(result[0].lastKnownPrice).toBeDefined();
|
||||
expect(result[0].lastKnownPrice?.storeName).toBe('Walgreens');
|
||||
});
|
||||
|
||||
it('attaches cheapestOption from compareStores', async () => {
|
||||
mockRegimensService.calculateBurnRates.mockResolvedValue([
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
dailyConsumption: 2,
|
||||
totalInCabinet: 5,
|
||||
daysUntilEmpty: 2,
|
||||
},
|
||||
]);
|
||||
mockCabinetRepo.getAggregateSummary.mockResolvedValue([]);
|
||||
mockPricesRepo.getLatestForMedicine.mockResolvedValue(null);
|
||||
mockPricesRepo.compareStores.mockResolvedValue([
|
||||
{
|
||||
storeId: 'st-1',
|
||||
storeName: 'CVS',
|
||||
latestPrice: 8,
|
||||
latestPricePerUnit: 0.08,
|
||||
currency: 'USD',
|
||||
date: new Date(),
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await service.getAlerts('hh1', 'user-1', 7);
|
||||
|
||||
expect(result[0].cheapestOption).toBeDefined();
|
||||
expect(result[0].cheapestOption?.storeName).toBe('CVS');
|
||||
});
|
||||
|
||||
it('includes pendingOrderStock and daysUntilEmptyWithOrders from ordered purchases', async () => {
|
||||
mockRegimensService.calculateBurnRates.mockResolvedValue([
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
dailyConsumption: 2,
|
||||
totalInCabinet: 4,
|
||||
daysUntilEmpty: 2,
|
||||
},
|
||||
]);
|
||||
mockCabinetRepo.getAggregateSummary.mockResolvedValue([]);
|
||||
mockPricesRepo.getLatestForMedicine.mockResolvedValue(null);
|
||||
mockPricesRepo.compareStores.mockResolvedValue([]);
|
||||
mockPurchasesRepo.getPendingMedicineStock.mockResolvedValue([
|
||||
{ medicineId: 'med-1', totalUnits: 60 },
|
||||
]);
|
||||
|
||||
const result = await service.getAlerts('hh1', 'user-1', 7);
|
||||
|
||||
expect(result[0].pendingOrderStock).toBe(60);
|
||||
expect(result[0].daysUntilEmptyWithOrders).toBe(32); // (4 + 60) / 2
|
||||
});
|
||||
|
||||
it('excludes medicines with null daysUntilEmpty', async () => {
|
||||
mockRegimensService.calculateBurnRates.mockResolvedValue([
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
dailyConsumption: 2,
|
||||
totalInCabinet: 0,
|
||||
daysUntilEmpty: null,
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await service.getAlerts('hh1', 'user-1', 7);
|
||||
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createList', () => {
|
||||
it('creates list with provided items', async () => {
|
||||
const list = { _id: 'rl-1', name: 'My List', items: [], status: 'active' };
|
||||
mockRepo.create.mockResolvedValue(list);
|
||||
|
||||
const result = await service.createList(
|
||||
{
|
||||
name: 'My List',
|
||||
fromAlerts: false,
|
||||
thresholdDays: 7,
|
||||
items: [
|
||||
{ medicineId: 'med-1', medicineName: 'Aspirin', quantity: 30, unit: 'tablet' as never },
|
||||
],
|
||||
},
|
||||
'hh1',
|
||||
'user-1',
|
||||
);
|
||||
|
||||
expect(result).toEqual(list);
|
||||
expect(mockRepo.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 'My List', householdId: 'hh1' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('creates list with no items when neither fromAlerts nor items provided', async () => {
|
||||
mockRepo.create.mockResolvedValue({ _id: 'rl-1', items: [] });
|
||||
|
||||
await service.createList(
|
||||
{ name: 'Empty List', fromAlerts: false, thresholdDays: 7 },
|
||||
'hh1',
|
||||
'user-1',
|
||||
);
|
||||
|
||||
expect(mockRepo.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ items: [], totalEstimatedCost: undefined }),
|
||||
);
|
||||
});
|
||||
|
||||
it('computes totalEstimatedCost from items with estimatedPrice', async () => {
|
||||
mockRepo.create.mockResolvedValue({ _id: 'rl-1', items: [] });
|
||||
|
||||
await service.createList(
|
||||
{
|
||||
name: 'Priced List',
|
||||
fromAlerts: false,
|
||||
thresholdDays: 7,
|
||||
items: [
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
quantity: 30,
|
||||
unit: 'tablet' as never,
|
||||
estimatedPrice: 10,
|
||||
},
|
||||
{
|
||||
medicineId: 'med-2',
|
||||
medicineName: 'Ibuprofen',
|
||||
quantity: 20,
|
||||
unit: 'tablet' as never,
|
||||
estimatedPrice: 8,
|
||||
},
|
||||
],
|
||||
},
|
||||
'hh1',
|
||||
'user-1',
|
||||
);
|
||||
|
||||
expect(mockRepo.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ totalEstimatedCost: 18 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('creates list from alerts when fromAlerts is true', async () => {
|
||||
mockRegimensService.calculateBurnRates.mockResolvedValue([
|
||||
{
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
dailyConsumption: 2,
|
||||
totalInCabinet: 5,
|
||||
daysUntilEmpty: 2,
|
||||
},
|
||||
]);
|
||||
mockCabinetRepo.getAggregateSummary.mockResolvedValue([]);
|
||||
mockPricesRepo.getLatestForMedicine.mockResolvedValue(null);
|
||||
mockPricesRepo.compareStores.mockResolvedValue([]);
|
||||
mockRepo.create.mockResolvedValue({ _id: 'rl-1', items: [] });
|
||||
|
||||
await service.createList(
|
||||
{ name: 'Auto List', fromAlerts: true, thresholdDays: 7 },
|
||||
'hh1',
|
||||
'user-1',
|
||||
);
|
||||
|
||||
expect(mockRepo.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
items: expect.arrayContaining([expect.objectContaining({ medicineId: 'med-1' })]),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('list', () => {
|
||||
it('delegates to repository', async () => {
|
||||
const result = { data: [], pagination: { cursor: null, hasMore: false } };
|
||||
mockRepo.findByHousehold.mockResolvedValue(result);
|
||||
|
||||
const response = await service.list('hh1', { limit: 20 });
|
||||
|
||||
expect(response).toEqual(result);
|
||||
expect(mockRepo.findByHousehold).toHaveBeenCalledWith('hh1', { limit: 20 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getById', () => {
|
||||
it('returns list when found', async () => {
|
||||
const list = { _id: 'rl-1', name: 'My List' };
|
||||
mockRepo.findById.mockResolvedValue(list);
|
||||
|
||||
expect(await service.getById('rl-1', 'hh1')).toEqual(list);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when not found', async () => {
|
||||
mockRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.getById('missing', 'hh1')).rejects.toThrow('Refill list not found');
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateList', () => {
|
||||
it('updates and returns list', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'rl-1' });
|
||||
const updated = { _id: 'rl-1', name: 'Updated' };
|
||||
mockRepo.update.mockResolvedValue(updated);
|
||||
|
||||
const result = await service.updateList('rl-1', 'hh1', { name: 'Updated' });
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when list not found', async () => {
|
||||
mockRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.updateList('missing', 'hh1', {})).rejects.toThrow(
|
||||
'Refill list not found',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when update returns null', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'rl-1' });
|
||||
mockRepo.update.mockResolvedValue(null);
|
||||
|
||||
await expect(service.updateList('rl-1', 'hh1', {})).rejects.toThrow('Refill list not found');
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateItem', () => {
|
||||
it('updates item and returns list', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'rl-1' });
|
||||
const updated = { _id: 'rl-1', items: [{ _id: 'item-1', checked: true }] };
|
||||
mockRepo.updateItem.mockResolvedValue(updated);
|
||||
|
||||
const result = await service.updateItem('rl-1', 'hh1', 'item-1', { checked: true });
|
||||
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
|
||||
it('sets checkedAt when checked is true', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'rl-1' });
|
||||
mockRepo.updateItem.mockResolvedValue({ _id: 'rl-1', items: [] });
|
||||
|
||||
await service.updateItem('rl-1', 'hh1', 'item-1', { checked: true });
|
||||
|
||||
expect(mockRepo.updateItem).toHaveBeenCalledWith(
|
||||
'rl-1',
|
||||
'hh1',
|
||||
'item-1',
|
||||
expect.objectContaining({ checkedAt: expect.any(Date) }),
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when list not found', async () => {
|
||||
mockRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.updateItem('missing', 'hh1', 'item-1', {})).rejects.toThrow(
|
||||
'Refill list not found',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when item not found', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'rl-1' });
|
||||
mockRepo.updateItem.mockResolvedValue(null);
|
||||
|
||||
await expect(service.updateItem('rl-1', 'hh1', 'bad-item', {})).rejects.toThrow(
|
||||
'Refill list or item not found',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addToCabinet', () => {
|
||||
it('adds checked items to cabinet', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'rl-1',
|
||||
items: [
|
||||
{
|
||||
_id: { toString: () => 'item-1' },
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
quantity: 30,
|
||||
unit: 'tablet',
|
||||
checked: true,
|
||||
addedToCabinet: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
mockCabinetService.addItem.mockResolvedValue({ _id: 'ci-1' });
|
||||
mockRepo.markItemsAddedToCabinet.mockResolvedValue({ _id: 'rl-1' });
|
||||
|
||||
const result = await service.addToCabinet('rl-1', 'hh1', 'user-1');
|
||||
|
||||
expect(result.addedCount).toBe(1);
|
||||
expect(mockCabinetService.addItem).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('computes unitPrice when actualPrice is set', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'rl-1',
|
||||
items: [
|
||||
{
|
||||
_id: { toString: () => 'item-1' },
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
quantity: 30,
|
||||
unit: 'tablet',
|
||||
actualPrice: 9,
|
||||
checked: true,
|
||||
addedToCabinet: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
mockCabinetService.addItem.mockResolvedValue({ _id: 'ci-1' });
|
||||
mockRepo.markItemsAddedToCabinet.mockResolvedValue({ _id: 'rl-1' });
|
||||
|
||||
await service.addToCabinet('rl-1', 'hh1', 'user-1');
|
||||
|
||||
expect(mockCabinetService.addItem).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ unitPrice: 0.3, totalPrice: 9 }),
|
||||
'hh1',
|
||||
'user-1',
|
||||
);
|
||||
});
|
||||
|
||||
it('returns zero count when no checked items', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'rl-1',
|
||||
items: [
|
||||
{
|
||||
_id: 'item-1',
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
quantity: 30,
|
||||
unit: 'tablet',
|
||||
checked: false,
|
||||
addedToCabinet: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.addToCabinet('rl-1', 'hh1', 'user-1');
|
||||
|
||||
expect(result.addedCount).toBe(0);
|
||||
expect(mockCabinetService.addItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips already-added items', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'rl-1',
|
||||
items: [
|
||||
{
|
||||
_id: 'item-1',
|
||||
medicineId: 'med-1',
|
||||
medicineName: 'Aspirin',
|
||||
quantity: 30,
|
||||
unit: 'tablet',
|
||||
checked: true,
|
||||
addedToCabinet: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.addToCabinet('rl-1', 'hh1', 'user-1');
|
||||
|
||||
expect(result.addedCount).toBe(0);
|
||||
expect(mockCabinetService.addItem).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getStoreComparison', () => {
|
||||
it('returns store comparisons for list items', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'rl-1',
|
||||
items: [{ medicineId: 'med-1' }, { medicineId: 'med-2' }],
|
||||
});
|
||||
mockPricesRepo.compareStores
|
||||
.mockResolvedValueOnce([{ storeId: 'st-1', storeName: 'CVS' }])
|
||||
.mockResolvedValueOnce([]);
|
||||
|
||||
const result = await service.getStoreComparison('rl-1', 'hh1');
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].medicineId).toBe('med-1');
|
||||
});
|
||||
|
||||
it('deduplicates medicine ids', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'rl-1',
|
||||
items: [{ medicineId: 'med-1' }, { medicineId: 'med-1' }],
|
||||
});
|
||||
mockPricesRepo.compareStores.mockResolvedValue([{ storeId: 'st-1', storeName: 'CVS' }]);
|
||||
|
||||
const result = await service.getStoreComparison('rl-1', 'hh1');
|
||||
|
||||
expect(mockPricesRepo.compareStores).toHaveBeenCalledTimes(1);
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue