Tests refactor

This commit is contained in:
Aerilyn Weber 2026-05-19 11:06:03 +09:00
parent 245520fb50
commit 99134d8556
165 changed files with 911 additions and 531 deletions

View file

@ -0,0 +1,192 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { DosageUnit, MedicineProductSource } from '@meshitrack/shared';
const {
mockExec,
_mockLean,
mockFind,
mockFindOne,
mockFindOneAndUpdate,
mockSave,
_mockSort,
_mockLimit,
mockCountDocuments,
} = vi.hoisted(() => {
const mockExec = vi.fn();
const mockLean = vi.fn(() => ({ exec: mockExec }));
const mockLimit = vi.fn(() => ({ lean: mockLean }));
const mockSort = vi.fn(() => ({ limit: mockLimit }));
const mockCountDocuments = vi.fn();
return {
mockExec,
mockLean,
mockFind: vi.fn(() => ({ sort: mockSort })),
mockFindOne: vi.fn(() => ({ lean: mockLean })),
mockFindOneAndUpdate: vi.fn(() => ({ exec: mockExec })),
mockSave: vi.fn(),
mockSort,
mockLimit,
mockCountDocuments,
};
});
vi.mock('../../../src/schemas/medicine-product.schema.js', () => {
class MockMedicineProductModel {
_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: 'mp-new', ...this._data };
}
static find = mockFind;
static findOne = mockFindOne;
static findOneAndUpdate = mockFindOneAndUpdate;
static countDocuments = vi.fn(() => ({ exec: mockCountDocuments }));
}
return { MedicineProductModel: MockMedicineProductModel };
});
import { MedicineProductsRepository } from '../../../src/modules/medicine-products/medicine-products.repository.js';
describe(MedicineProductsRepository.name, () => {
let repo: MedicineProductsRepository;
beforeEach(() => {
vi.clearAllMocks();
repo = new MedicineProductsRepository();
});
describe('findByMedicine', () => {
it('returns paginated results', async () => {
const items = [
{ _id: 'mp-1', brand: 'CVS' },
{ _id: 'mp-2', brand: 'Kirkland' },
];
mockExec.mockResolvedValue(items);
const result = await repo.findByMedicine('hh1', 'med-1', { limit: 20 });
expect(mockFind).toHaveBeenCalledWith({
householdId: 'hh1',
medicineId: 'med-1',
isDeleted: false,
});
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(false);
});
it('detects hasMore when extra item returned', async () => {
const items = Array.from({ length: 3 }, (_, i) => ({ _id: `mp-${i}`, brand: `Brand ${i}` }));
mockExec.mockResolvedValue(items);
const result = await repo.findByMedicine('hh1', 'med-1', { 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('mp-5').toString('base64');
await repo.findByMedicine('hh1', 'med-1', { cursor, limit: 20 });
expect(mockFind).toHaveBeenCalledWith(expect.objectContaining({ _id: { $gt: 'mp-5' } }));
});
it('returns null cursor when no data', async () => {
mockExec.mockResolvedValue([]);
const result = await repo.findByMedicine('hh1', 'med-1', { limit: 20 });
expect(result.pagination.cursor).toBeNull();
expect(result.pagination.hasMore).toBe(false);
});
});
describe('findById', () => {
it('finds by id and householdId', async () => {
const product = { _id: 'mp-1', brand: 'CVS' };
mockExec.mockResolvedValue(product);
const result = await repo.findById('mp-1', 'hh1');
expect(mockFindOne).toHaveBeenCalledWith({
_id: 'mp-1',
householdId: 'hh1',
isDeleted: false,
});
expect(result).toEqual(product);
});
});
describe('create', () => {
it('creates a medicine product', async () => {
mockSave.mockResolvedValue({});
const data = {
brand: 'CVS Health',
packageSize: 90,
packageUnit: DosageUnit.TABLET,
source: MedicineProductSource.MANUAL,
};
const result = await repo.create(data, 'hh1', 'med-1', 'Metformin', 'kc-1');
expect(mockSave).toHaveBeenCalled();
expect(result).toMatchObject({
brand: 'CVS Health',
householdId: 'hh1',
medicineId: 'med-1',
medicineName: 'Metformin',
createdBy: 'kc-1',
});
});
});
describe('update', () => {
it('updates a medicine product', async () => {
mockExec.mockResolvedValue({ _id: 'mp-1', brand: 'Updated' });
const result = await repo.update('mp-1', 'hh1', { brand: 'Updated' });
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
{ _id: 'mp-1', householdId: 'hh1', isDeleted: false },
{ $set: { brand: 'Updated' } },
{ new: true, lean: true },
);
expect(result).toEqual({ _id: 'mp-1', brand: 'Updated' });
});
});
describe('softDelete', () => {
it('sets isDeleted to true', async () => {
mockExec.mockResolvedValue({ _id: 'mp-1', isDeleted: true });
await repo.softDelete('mp-1', 'hh1');
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
{ _id: 'mp-1', householdId: 'hh1', isDeleted: false },
{ $set: { isDeleted: true } },
{ new: true, lean: true },
);
});
});
describe('countByMedicineId', () => {
it('returns count of non-deleted products for medicine', async () => {
mockCountDocuments.mockResolvedValue(3);
const result = await repo.countByMedicineId('med-1');
expect(result).toBe(3);
});
});
});

View file

@ -0,0 +1,250 @@
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 { DosageUnit, MedicineProductSource } 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 {
mockFindByMedicine,
mockFindById,
mockCreate,
mockUpdate,
mockSoftDelete,
mockMedicineFindById,
} = vi.hoisted(() => ({
mockFindByMedicine: vi.fn(),
mockFindById: vi.fn(),
mockCreate: vi.fn(),
mockUpdate: vi.fn(),
mockSoftDelete: vi.fn(),
mockMedicineFindById: vi.fn(),
}));
vi.mock('../../../src/modules/medicine-products/medicine-products.repository.js', () => ({
MedicineProductsRepository: class {
findByMedicine = mockFindByMedicine;
findById = mockFindById;
create = mockCreate;
update = mockUpdate;
softDelete = mockSoftDelete;
},
}));
vi.mock('../../../src/modules/medicines/medicines.repository.js', () => ({
MedicinesRepository: class {
findById = mockMedicineFindById;
},
}));
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 makeFakeProduct(overrides = {}) {
return {
_id: 'mp-1',
householdId: 'hh1',
medicineId: 'med-1',
medicineName: 'Metformin',
brand: 'CVS Health',
packageSize: 90,
packageUnit: DosageUnit.TABLET,
source: MedicineProductSource.MANUAL,
createdBy: 'kc-1',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
...overrides,
};
}
describe('medicine-products.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(medicinesRoutes);
await instance.register(medicineProductsRoutes);
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/medicines/:medicineId/products', () => {
it('returns paginated list', async () => {
const product = makeFakeProduct();
mockFindByMedicine.mockResolvedValue({
data: [product],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/medicines/med-1/products',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data).toHaveLength(1);
expect(body.data[0].brand).toBe('CVS Health');
expect(body.pagination.hasMore).toBe(false);
});
it('handles ObjectId and Date objects in response', async () => {
const product = makeFakeProduct({
_id: { toString: () => 'mp-obj' },
createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
updatedAt: { toISOString: () => '2024-01-02T00:00:00.000Z' },
manufacturer: 'Pfizer',
imageUrl: 'https://example.com/img.png',
notes: 'Store in cool place',
});
mockFindByMedicine.mockResolvedValue({
data: [product],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/medicines/med-1/products',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data[0]._id).toBe('mp-obj');
expect(body.data[0].createdAt).toBe('2024-01-01T00:00:00.000Z');
expect(body.data[0].manufacturer).toBe('Pfizer');
expect(body.data[0].imageUrl).toBe('https://example.com/img.png');
expect(body.data[0].notes).toBe('Store in cool place');
});
});
describe('GET /api/v1/households/:householdId/medicine-products/:id', () => {
it('returns a product', async () => {
mockFindById.mockResolvedValue(makeFakeProduct());
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/medicine-products/mp-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(res.json().brand).toBe('CVS Health');
});
it('includes concentration fields in response when present', async () => {
mockFindById.mockResolvedValue(
makeFakeProduct({ concentration: 5, concentrationUnit: 'mg/ml' }),
);
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/medicine-products/mp-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(res.json().concentration).toBe(5);
expect(res.json().concentrationUnit).toBe('mg/ml');
});
});
describe('POST /api/v1/households/:householdId/medicines/:medicineId/products', () => {
it('creates a product', async () => {
mockMedicineFindById.mockResolvedValue({ _id: 'med-1', name: 'Metformin' });
mockCreate.mockResolvedValue(makeFakeProduct());
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/medicines/med-1/products',
headers: authHeaders,
payload: {
brand: 'CVS Health',
packageSize: 90,
packageUnit: DosageUnit.TABLET,
},
});
expect(res.statusCode).toBe(201);
expect(res.json().brand).toBe('CVS Health');
});
});
describe('PATCH /api/v1/households/:householdId/medicine-products/:id', () => {
it('updates a product', async () => {
mockFindById.mockResolvedValue(makeFakeProduct());
mockUpdate.mockResolvedValue(makeFakeProduct({ brand: 'Updated' }));
const res = await app.inject({
method: 'PATCH',
url: '/api/v1/households/hh1/medicine-products/mp-1',
headers: authHeaders,
payload: { brand: 'Updated' },
});
expect(res.statusCode).toBe(200);
expect(res.json().brand).toBe('Updated');
});
});
describe('DELETE /api/v1/households/:householdId/medicine-products/:id', () => {
it('soft deletes a product', async () => {
mockFindById.mockResolvedValue(makeFakeProduct());
mockSoftDelete.mockResolvedValue(makeFakeProduct({ isDeleted: true }));
const res = await app.inject({
method: 'DELETE',
url: '/api/v1/households/hh1/medicine-products/mp-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(204);
});
});
});

View file

@ -0,0 +1,140 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { MedicineProductsService } from '../../../src/modules/medicine-products/medicine-products.service.js';
import { NotFoundError } from '../../../src/common/errors.js';
import { DosageUnit, MedicineProductSource } from '@meshitrack/shared';
describe(MedicineProductsService.name, () => {
const mockProductsRepo = {
findByMedicine: vi.fn(),
findById: vi.fn(),
create: vi.fn(),
update: vi.fn(),
softDelete: vi.fn(),
};
const mockMedicinesRepo = {
findById: vi.fn(),
};
let service: MedicineProductsService;
beforeEach(() => {
vi.clearAllMocks();
service = new MedicineProductsService({
medicineProductsRepository: mockProductsRepo as never,
medicinesRepository: mockMedicinesRepo as never,
});
});
describe('listByMedicine', () => {
it('delegates to repository', async () => {
const expected = { data: [], pagination: { cursor: null, hasMore: false } };
mockProductsRepo.findByMedicine.mockResolvedValue(expected);
const result = await service.listByMedicine('hh1', 'med-1', { limit: 20 });
expect(mockProductsRepo.findByMedicine).toHaveBeenCalledWith('hh1', 'med-1', { limit: 20 });
expect(result).toEqual(expected);
});
});
describe('getById', () => {
it('returns product when found', async () => {
const product = { _id: 'mp-1', brand: 'CVS' };
mockProductsRepo.findById.mockResolvedValue(product);
const result = await service.getById('mp-1', 'hh1');
expect(result).toEqual(product);
});
it('throws NotFoundError when not found', async () => {
mockProductsRepo.findById.mockResolvedValue(null);
await expect(service.getById('missing', 'hh1')).rejects.toThrow(NotFoundError);
});
});
describe('create', () => {
const data = {
brand: 'CVS Health',
packageSize: 90,
packageUnit: DosageUnit.TABLET,
source: MedicineProductSource.MANUAL,
};
it('creates when parent medicine exists', async () => {
mockMedicinesRepo.findById.mockResolvedValue({ _id: 'med-1', name: 'Metformin' });
mockProductsRepo.create.mockResolvedValue({
_id: 'mp-1',
...data,
medicineName: 'Metformin',
});
const result = await service.create(data, 'hh1', 'med-1', 'kc-1');
expect(mockMedicinesRepo.findById).toHaveBeenCalledWith('med-1', 'hh1');
expect(mockProductsRepo.create).toHaveBeenCalledWith(
data,
'hh1',
'med-1',
'Metformin',
'kc-1',
);
expect(result._id).toBe('mp-1');
});
it('throws NotFoundError when parent medicine does not exist', async () => {
mockMedicinesRepo.findById.mockResolvedValue(null);
await expect(service.create(data, 'hh1', 'missing', 'kc-1')).rejects.toThrow(NotFoundError);
expect(mockProductsRepo.create).not.toHaveBeenCalled();
});
});
describe('update', () => {
it('updates a product', async () => {
mockProductsRepo.findById.mockResolvedValue({ _id: 'mp-1', brand: 'CVS' });
mockProductsRepo.update.mockResolvedValue({ _id: 'mp-1', brand: 'Updated' });
const result = await service.update('mp-1', 'hh1', { brand: 'Updated' });
expect(result.brand).toBe('Updated');
});
it('throws NotFoundError when product does not exist', async () => {
mockProductsRepo.findById.mockResolvedValue(null);
await expect(service.update('missing', 'hh1', { brand: 'X' })).rejects.toThrow(NotFoundError);
});
it('throws NotFoundError when update returns null', async () => {
mockProductsRepo.findById.mockResolvedValue({ _id: 'mp-1' });
mockProductsRepo.update.mockResolvedValue(null);
await expect(service.update('mp-1', 'hh1', { brand: 'X' })).rejects.toThrow(NotFoundError);
});
});
describe('delete', () => {
it('soft deletes a product', async () => {
mockProductsRepo.findById.mockResolvedValue({ _id: 'mp-1' });
mockProductsRepo.softDelete.mockResolvedValue({ _id: 'mp-1', isDeleted: true });
await service.delete('mp-1', 'hh1');
expect(mockProductsRepo.softDelete).toHaveBeenCalledWith('mp-1', 'hh1');
});
it('throws NotFoundError when not found', async () => {
mockProductsRepo.findById.mockResolvedValue(null);
await expect(service.delete('missing', 'hh1')).rejects.toThrow(NotFoundError);
});
it('throws NotFoundError when softDelete returns null', async () => {
mockProductsRepo.findById.mockResolvedValue({ _id: 'mp-1' });
mockProductsRepo.softDelete.mockResolvedValue(null);
await expect(service.delete('mp-1', 'hh1')).rejects.toThrow(NotFoundError);
});
});
});