Tests refactor
This commit is contained in:
parent
245520fb50
commit
99134d8556
165 changed files with 911 additions and 531 deletions
|
|
@ -0,0 +1,215 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { MedicineForm, StrengthUnit, MedicineCategory } from '@meshitrack/shared';
|
||||
|
||||
const {
|
||||
mockExec,
|
||||
_mockLean,
|
||||
mockFind,
|
||||
mockFindOne,
|
||||
mockFindOneAndUpdate,
|
||||
mockSave,
|
||||
_mockSort,
|
||||
_mockLimit,
|
||||
} = vi.hoisted(() => {
|
||||
const mockExec = vi.fn();
|
||||
const mockLean = vi.fn(() => ({ exec: mockExec }));
|
||||
const mockLimit = vi.fn(() => ({ lean: mockLean }));
|
||||
const mockSort = vi.fn(() => ({ limit: mockLimit }));
|
||||
return {
|
||||
mockExec,
|
||||
mockLean,
|
||||
mockFind: vi.fn(() => ({ sort: mockSort })),
|
||||
mockFindOne: vi.fn(() => ({ lean: mockLean })),
|
||||
mockFindOneAndUpdate: vi.fn(() => ({ exec: mockExec })),
|
||||
mockSave: vi.fn(),
|
||||
mockSort,
|
||||
mockLimit,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../../src/schemas/medicine.schema.js', () => {
|
||||
class MockMedicineModel {
|
||||
_data: Record<string, unknown>;
|
||||
constructor(data: Record<string, unknown>) {
|
||||
this._data = data;
|
||||
Object.assign(this, data);
|
||||
}
|
||||
save() {
|
||||
mockSave();
|
||||
return Promise.resolve(this);
|
||||
}
|
||||
toObject() {
|
||||
return { _id: 'med-new', ...this._data };
|
||||
}
|
||||
static find = mockFind;
|
||||
static findOne = mockFindOne;
|
||||
static findOneAndUpdate = mockFindOneAndUpdate;
|
||||
}
|
||||
return { MedicineModel: MockMedicineModel };
|
||||
});
|
||||
|
||||
import { MedicinesRepository } from '../../../src/modules/medicines/medicines.repository.js';
|
||||
|
||||
describe(MedicinesRepository.name, () => {
|
||||
let repo: MedicinesRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new MedicinesRepository();
|
||||
});
|
||||
|
||||
describe('findByHousehold', () => {
|
||||
it('returns paginated results', async () => {
|
||||
const items = [
|
||||
{ _id: 'med-1', name: 'Aspirin' },
|
||||
{ _id: 'med-2', name: 'Ibuprofen' },
|
||||
];
|
||||
mockExec.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findByHousehold('hh1', { limit: 20 });
|
||||
|
||||
expect(mockFind).toHaveBeenCalledWith({ householdId: 'hh1', isDeleted: false });
|
||||
expect(result.data).toHaveLength(2);
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('applies partial name search when q is provided', async () => {
|
||||
mockExec.mockResolvedValue([]);
|
||||
|
||||
await repo.findByHousehold('hh1', { q: 'asp', limit: 20 });
|
||||
|
||||
expect(mockFind).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: { $regex: 'asp', $options: 'i' } }),
|
||||
);
|
||||
});
|
||||
|
||||
it('applies category filter', async () => {
|
||||
mockExec.mockResolvedValue([]);
|
||||
|
||||
await repo.findByHousehold('hh1', { category: MedicineCategory.PRESCRIPTION, limit: 20 });
|
||||
|
||||
expect(mockFind).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ category: MedicineCategory.PRESCRIPTION }),
|
||||
);
|
||||
});
|
||||
|
||||
it('applies form filter', async () => {
|
||||
mockExec.mockResolvedValue([]);
|
||||
|
||||
await repo.findByHousehold('hh1', { form: MedicineForm.TABLET, limit: 20 });
|
||||
|
||||
expect(mockFind).toHaveBeenCalledWith(expect.objectContaining({ form: MedicineForm.TABLET }));
|
||||
});
|
||||
|
||||
it('detects hasMore when extra item returned', async () => {
|
||||
const items = Array.from({ length: 3 }, (_, i) => ({ _id: `med-${i}`, name: `Med ${i}` }));
|
||||
mockExec.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('decodes cursor for pagination', async () => {
|
||||
mockExec.mockResolvedValue([]);
|
||||
const cursor = Buffer.from('med-5').toString('base64');
|
||||
|
||||
await repo.findByHousehold('hh1', { cursor, limit: 20 });
|
||||
|
||||
expect(mockFind).toHaveBeenCalledWith(expect.objectContaining({ _id: { $gt: 'med-5' } }));
|
||||
});
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('finds by id and householdId', async () => {
|
||||
const medicine = { _id: 'med-1', name: 'Aspirin' };
|
||||
mockExec.mockResolvedValue(medicine);
|
||||
|
||||
const result = await repo.findById('med-1', 'hh1');
|
||||
|
||||
expect(mockFindOne).toHaveBeenCalledWith({
|
||||
_id: 'med-1',
|
||||
householdId: 'hh1',
|
||||
isDeleted: false,
|
||||
});
|
||||
expect(result).toEqual(medicine);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findDuplicate', () => {
|
||||
it('finds medicine with matching fields', async () => {
|
||||
mockExec.mockResolvedValue({ _id: 'med-1' });
|
||||
|
||||
const result = await repo.findDuplicate('hh1', 'Aspirin', 500, 'mg', 'tablet');
|
||||
|
||||
expect(mockFindOne).toHaveBeenCalledWith({
|
||||
householdId: 'hh1',
|
||||
name: 'Aspirin',
|
||||
strength: 500,
|
||||
strengthUnit: 'mg',
|
||||
form: 'tablet',
|
||||
isDeleted: false,
|
||||
});
|
||||
expect(result).toBeTruthy();
|
||||
});
|
||||
|
||||
it('excludes specified id', async () => {
|
||||
mockExec.mockResolvedValue(null);
|
||||
|
||||
await repo.findDuplicate('hh1', 'Aspirin', 500, 'mg', 'tablet', 'med-1');
|
||||
|
||||
expect(mockFindOne).toHaveBeenCalledWith(expect.objectContaining({ _id: { $ne: 'med-1' } }));
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('creates a medicine', async () => {
|
||||
mockSave.mockResolvedValue({});
|
||||
|
||||
const data = {
|
||||
name: 'Aspirin',
|
||||
form: MedicineForm.TABLET,
|
||||
strength: 500,
|
||||
strengthUnit: StrengthUnit.MG,
|
||||
category: MedicineCategory.OTC,
|
||||
tags: [],
|
||||
};
|
||||
|
||||
const result = await repo.create(data, 'hh1', 'kc-1');
|
||||
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
expect(result).toMatchObject({ name: 'Aspirin', householdId: 'hh1', createdBy: 'kc-1' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('updates a medicine', async () => {
|
||||
mockExec.mockResolvedValue({ _id: 'med-1', name: 'Updated' });
|
||||
|
||||
const result = await repo.update('med-1', 'hh1', { name: 'Updated' });
|
||||
|
||||
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ _id: 'med-1', householdId: 'hh1', isDeleted: false },
|
||||
{ $set: { name: 'Updated' } },
|
||||
{ new: true, lean: true },
|
||||
);
|
||||
expect(result).toEqual({ _id: 'med-1', name: 'Updated' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('softDelete', () => {
|
||||
it('sets isDeleted to true', async () => {
|
||||
mockExec.mockResolvedValue({ _id: 'med-1', isDeleted: true });
|
||||
|
||||
await repo.softDelete('med-1', 'hh1');
|
||||
|
||||
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ _id: 'med-1', householdId: 'hh1', isDeleted: false },
|
||||
{ $set: { isDeleted: true } },
|
||||
{ new: true, lean: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
247
packages/api/tests/modules/medicines/medicines.routes.test.ts
Normal file
247
packages/api/tests/modules/medicines/medicines.routes.test.ts
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
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';
|
||||
import { MedicineForm, StrengthUnit, MedicineCategory } from '@meshitrack/shared';
|
||||
|
||||
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 {
|
||||
mockFindByHousehold,
|
||||
mockFindById,
|
||||
mockFindDuplicate,
|
||||
mockCreate,
|
||||
mockUpdate,
|
||||
mockSoftDelete,
|
||||
mockCountByMedicineId,
|
||||
} = vi.hoisted(() => ({
|
||||
mockFindByHousehold: vi.fn(),
|
||||
mockFindById: vi.fn(),
|
||||
mockFindDuplicate: vi.fn(),
|
||||
mockCreate: vi.fn(),
|
||||
mockUpdate: vi.fn(),
|
||||
mockSoftDelete: vi.fn(),
|
||||
mockCountByMedicineId: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/medicines/medicines.repository.js', () => ({
|
||||
MedicinesRepository: class {
|
||||
findByHousehold = mockFindByHousehold;
|
||||
findById = mockFindById;
|
||||
findDuplicate = mockFindDuplicate;
|
||||
create = mockCreate;
|
||||
update = mockUpdate;
|
||||
softDelete = mockSoftDelete;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/medicine-products/medicine-products.repository.js', () => ({
|
||||
MedicineProductsRepository: class {
|
||||
countByMedicineId = mockCountByMedicineId;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/medicine-products/medicine-products.service.js', () => ({
|
||||
MedicineProductsService: class {
|
||||
listByMedicine = vi.fn();
|
||||
getById = vi.fn();
|
||||
create = vi.fn();
|
||||
update = vi.fn();
|
||||
delete = 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 medicinesRoutes from '../../../src/modules/medicines/medicines.routes.js';
|
||||
import medicineProductsRoutes from '../../../src/modules/medicine-products/medicine-products.routes.js';
|
||||
|
||||
function makeFakeMedicine(overrides = {}) {
|
||||
return {
|
||||
_id: 'med-1',
|
||||
householdId: 'hh1',
|
||||
name: 'Metformin',
|
||||
form: MedicineForm.TABLET,
|
||||
strength: 500,
|
||||
strengthUnit: StrengthUnit.MG,
|
||||
category: MedicineCategory.PRESCRIPTION,
|
||||
tags: [],
|
||||
createdBy: 'kc-1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('medicines.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(medicineProductsRoutes);
|
||||
await instance.register(medicinesRoutes);
|
||||
await instance.ready();
|
||||
return instance;
|
||||
}
|
||||
|
||||
const authHeaders = { authorization: 'Bearer valid-token' };
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
mockCountByMedicineId.mockResolvedValue(0);
|
||||
app = await buildTestApp();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/medicines', () => {
|
||||
it('returns paginated list', async () => {
|
||||
const medicine = makeFakeMedicine();
|
||||
mockFindByHousehold.mockResolvedValue({
|
||||
data: [medicine],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/medicines',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].name).toBe('Metformin');
|
||||
expect(body.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('handles ObjectId and Date objects in response', async () => {
|
||||
const medicine = makeFakeMedicine({
|
||||
_id: { toString: () => 'med-obj' },
|
||||
createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
|
||||
updatedAt: { toISOString: () => '2024-01-02T00:00:00.000Z' },
|
||||
notes: 'Take with food',
|
||||
});
|
||||
mockFindByHousehold.mockResolvedValue({
|
||||
data: [medicine],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/medicines',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data[0]._id).toBe('med-obj');
|
||||
expect(body.data[0].createdAt).toBe('2024-01-01T00:00:00.000Z');
|
||||
expect(body.data[0].notes).toBe('Take with food');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/medicines/:id', () => {
|
||||
it('returns a medicine', async () => {
|
||||
mockFindById.mockResolvedValue(makeFakeMedicine());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/medicines/med-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().name).toBe('Metformin');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/medicines', () => {
|
||||
it('creates a medicine', async () => {
|
||||
mockFindDuplicate.mockResolvedValue(null);
|
||||
mockCreate.mockResolvedValue(makeFakeMedicine());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/medicines',
|
||||
headers: authHeaders,
|
||||
payload: {
|
||||
name: 'Metformin',
|
||||
form: MedicineForm.TABLET,
|
||||
strength: 500,
|
||||
strengthUnit: StrengthUnit.MG,
|
||||
category: MedicineCategory.PRESCRIPTION,
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(res.json().name).toBe('Metformin');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/households/:householdId/medicines/:id', () => {
|
||||
it('updates a medicine', async () => {
|
||||
mockFindById.mockResolvedValue(makeFakeMedicine());
|
||||
mockFindDuplicate.mockResolvedValue(null);
|
||||
mockUpdate.mockResolvedValue(makeFakeMedicine({ name: 'Updated' }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/medicines/med-1',
|
||||
headers: authHeaders,
|
||||
payload: { name: 'Updated' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().name).toBe('Updated');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/households/:householdId/medicines/:id', () => {
|
||||
it('soft deletes a medicine', async () => {
|
||||
mockFindById.mockResolvedValue(makeFakeMedicine());
|
||||
mockSoftDelete.mockResolvedValue(makeFakeMedicine({ isDeleted: true }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/households/hh1/medicines/med-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(204);
|
||||
});
|
||||
});
|
||||
});
|
||||
206
packages/api/tests/modules/medicines/medicines.service.test.ts
Normal file
206
packages/api/tests/modules/medicines/medicines.service.test.ts
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { MedicinesService } from '../../../src/modules/medicines/medicines.service.js';
|
||||
import { NotFoundError, ConflictError } from '../../../src/common/errors.js';
|
||||
import { MedicineForm, StrengthUnit, MedicineCategory } from '@meshitrack/shared';
|
||||
|
||||
describe(MedicinesService.name, () => {
|
||||
const mockRepo = {
|
||||
findByHousehold: vi.fn(),
|
||||
findById: vi.fn(),
|
||||
findDuplicate: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
softDelete: vi.fn(),
|
||||
};
|
||||
|
||||
const mockProductsRepo = {
|
||||
countByMedicineId: vi.fn(),
|
||||
};
|
||||
|
||||
let service: MedicinesService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new MedicinesService({
|
||||
medicinesRepository: mockRepo as never,
|
||||
medicineProductsRepository: mockProductsRepo as never,
|
||||
});
|
||||
});
|
||||
|
||||
describe('list', () => {
|
||||
it('delegates to repository', async () => {
|
||||
const expected = { data: [], pagination: { cursor: null, hasMore: false } };
|
||||
mockRepo.findByHousehold.mockResolvedValue(expected);
|
||||
|
||||
const result = await service.list('hh1', { limit: 20 });
|
||||
|
||||
expect(mockRepo.findByHousehold).toHaveBeenCalledWith('hh1', { limit: 20 });
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getById', () => {
|
||||
it('returns medicine when found', async () => {
|
||||
const medicine = { _id: 'med-1', name: 'Aspirin' };
|
||||
mockRepo.findById.mockResolvedValue(medicine);
|
||||
|
||||
const result = await service.getById('med-1', 'hh1');
|
||||
expect(result).toEqual(medicine);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when not found', async () => {
|
||||
mockRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.getById('missing', 'hh1')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
const data = {
|
||||
name: 'Aspirin',
|
||||
form: MedicineForm.TABLET,
|
||||
strength: 500,
|
||||
strengthUnit: StrengthUnit.MG,
|
||||
category: MedicineCategory.OTC,
|
||||
tags: [],
|
||||
};
|
||||
|
||||
it('creates when no duplicate exists', async () => {
|
||||
mockRepo.findDuplicate.mockResolvedValue(null);
|
||||
mockRepo.create.mockResolvedValue({ _id: 'med-1', ...data });
|
||||
|
||||
const result = await service.create(data, 'hh1', 'kc-1');
|
||||
|
||||
expect(mockRepo.findDuplicate).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
'Aspirin',
|
||||
500,
|
||||
StrengthUnit.MG,
|
||||
MedicineForm.TABLET,
|
||||
);
|
||||
expect(result._id).toBe('med-1');
|
||||
});
|
||||
|
||||
it('throws ConflictError when duplicate exists', async () => {
|
||||
mockRepo.findDuplicate.mockResolvedValue({ _id: 'existing' });
|
||||
|
||||
await expect(service.create(data, 'hh1', 'kc-1')).rejects.toThrow(ConflictError);
|
||||
expect(mockRepo.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('updates a medicine', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'med-1',
|
||||
name: 'Aspirin',
|
||||
strength: 500,
|
||||
strengthUnit: StrengthUnit.MG,
|
||||
form: MedicineForm.TABLET,
|
||||
});
|
||||
mockRepo.findDuplicate.mockResolvedValue(null);
|
||||
mockRepo.update.mockResolvedValue({ _id: 'med-1', name: 'Updated' });
|
||||
|
||||
const result = await service.update('med-1', 'hh1', { name: 'Updated' });
|
||||
expect(result.name).toBe('Updated');
|
||||
});
|
||||
|
||||
it('throws NotFoundError when medicine does not exist', async () => {
|
||||
mockRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.update('missing', 'hh1', { name: 'X' })).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
it('throws ConflictError when update would create duplicate', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'med-1',
|
||||
name: 'Aspirin',
|
||||
strength: 500,
|
||||
strengthUnit: StrengthUnit.MG,
|
||||
form: MedicineForm.TABLET,
|
||||
});
|
||||
mockRepo.findDuplicate.mockResolvedValue({ _id: 'med-2' });
|
||||
|
||||
await expect(service.update('med-1', 'hh1', { name: 'Ibuprofen' })).rejects.toThrow(
|
||||
ConflictError,
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when repo update returns null', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'med-1', name: 'Aspirin' });
|
||||
mockRepo.update.mockResolvedValue(null);
|
||||
|
||||
await expect(service.update('med-1', 'hh1', { notes: 'Updated' })).rejects.toThrow(
|
||||
NotFoundError,
|
||||
);
|
||||
});
|
||||
|
||||
it('uses current name when name not provided in update', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'med-1',
|
||||
name: 'Aspirin',
|
||||
strength: 500,
|
||||
strengthUnit: StrengthUnit.MG,
|
||||
form: MedicineForm.TABLET,
|
||||
});
|
||||
mockRepo.findDuplicate.mockResolvedValue(null);
|
||||
mockRepo.update.mockResolvedValue({ _id: 'med-1', name: 'Aspirin', strength: 250 });
|
||||
|
||||
const result = await service.update('med-1', 'hh1', { strength: 250 });
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(mockRepo.findDuplicate).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
'Aspirin',
|
||||
250,
|
||||
StrengthUnit.MG,
|
||||
MedicineForm.TABLET,
|
||||
'med-1',
|
||||
);
|
||||
});
|
||||
|
||||
it('skips dedup check when no identity fields change', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'med-1', name: 'Aspirin' });
|
||||
mockRepo.update.mockResolvedValue({ _id: 'med-1', notes: 'Updated notes' });
|
||||
|
||||
await service.update('med-1', 'hh1', { notes: 'Updated notes' });
|
||||
|
||||
expect(mockRepo.findDuplicate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('soft deletes a medicine', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'med-1' });
|
||||
mockProductsRepo.countByMedicineId.mockResolvedValue(0);
|
||||
mockRepo.softDelete.mockResolvedValue({ _id: 'med-1', isDeleted: true });
|
||||
|
||||
await service.delete('med-1', 'hh1');
|
||||
|
||||
expect(mockProductsRepo.countByMedicineId).toHaveBeenCalledWith('med-1');
|
||||
expect(mockRepo.softDelete).toHaveBeenCalledWith('med-1', 'hh1');
|
||||
});
|
||||
|
||||
it('throws ConflictError when linked products exist', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'med-1' });
|
||||
mockProductsRepo.countByMedicineId.mockResolvedValue(3);
|
||||
|
||||
await expect(service.delete('med-1', 'hh1')).rejects.toThrow(ConflictError);
|
||||
expect(mockRepo.softDelete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws NotFoundError when not found', async () => {
|
||||
mockRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.delete('missing', 'hh1')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when softDelete returns null', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'med-1' });
|
||||
mockProductsRepo.countByMedicineId.mockResolvedValue(0);
|
||||
mockRepo.softDelete.mockResolvedValue(null);
|
||||
|
||||
await expect(service.delete('med-1', 'hh1')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue