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,162 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { PricesRepository } from '../../../src/modules/prices/prices.repository.js';
const { mockSave, MockPriceRecordModel } = vi.hoisted(() => {
const mockSave = vi.fn();
function MockModel(this: { save: typeof mockSave }, data: unknown) {
Object.assign(this, data);
this.save = mockSave;
}
Object.assign(MockModel, {
findOne: vi.fn(),
find: vi.fn(),
findOneAndUpdate: vi.fn(),
insertMany: vi.fn(),
aggregate: vi.fn(),
});
return { mockSave, MockPriceRecordModel: MockModel };
});
vi.mock('../../../src/schemas/price-record.schema.js', () => ({
PriceRecordModel: MockPriceRecordModel,
}));
const { PriceRecordModel } = await import('../../../src/schemas/price-record.schema.js');
function makeChain(result: unknown = null) {
return {
sort: vi.fn().mockReturnThis(),
limit: vi.fn().mockReturnThis(),
lean: vi.fn().mockReturnThis(),
exec: vi.fn().mockResolvedValue(result),
};
}
describe(PricesRepository.name, () => {
let repo: PricesRepository;
beforeEach(() => {
vi.clearAllMocks();
repo = new PricesRepository();
});
describe('create', () => {
it('saves and returns new document toObject', async () => {
const data = { householdId: 'h1', productId: 'p1', productName: 'Apple', storeId: 's1', storeName: 'Store', price: 1, currency: 'USD', quantity: 1, unit: 'g', pricePerUnit: 1, date: new Date(), createdBy: 'u1' };
mockSave.mockResolvedValue({ toObject: () => ({ ...data, _id: 'id1' }) });
const result = await repo.create(data);
expect(mockSave).toHaveBeenCalled();
expect(result._id).toBe('id1');
});
});
describe('createMany', () => {
it('inserts multiple records and returns mapped toObjects', async () => {
const inputs = [{ price: 1 }, { price: 2 }];
const returns = inputs.map((x, idx) => ({ ...x, _id: `id${idx}`, toObject: function() { return this; } }));
vi.mocked(PriceRecordModel.insertMany).mockResolvedValue(returns as any);
const result = await repo.createMany(inputs as any);
expect(PriceRecordModel.insertMany).toHaveBeenCalledWith(inputs);
expect(result).toHaveLength(2);
expect(result[0]._id).toBe('id0');
});
});
describe('findByProduct', () => {
it('applies complex filters and pagination cursor decoding/encoding', async () => {
const baseFilter = { householdId: 'h1', productId: 'prod1' };
const startDate = new Date('2026-01-01').toISOString();
const endDate = new Date('2026-01-10').toISOString();
const cursorId = '507f1f77bcf86cd799439011';
const cursorStr = Buffer.from(cursorId).toString('base64');
const mockItems = [
{ _id: '607f1f77bcf86cd799439012', price: 10 },
{ _id: '607f1f77bcf86cd799439013', price: 12 }
];
const chain = makeChain(mockItems);
vi.mocked(PriceRecordModel.find).mockReturnValue(chain as any);
const result = await repo.findByProduct('h1', 'prod1', {
storeId: 'st1',
startDate,
endDate,
cursor: cursorStr,
limit: 2
});
expect(PriceRecordModel.find).toHaveBeenCalledWith({
householdId: 'h1',
productId: 'prod1',
storeId: 'st1',
date: {
$gte: new Date(startDate),
$lte: new Date(endDate),
},
_id: { $lt: cursorId }
});
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(false);
});
it('correctly indicates hasMore and generates next base64 cursor', async () => {
const mockItems = [
{ _id: '607f1f77bcf86cd799439011', price: 10 },
{ _id: '607f1f77bcf86cd799439012', price: 11 },
{ _id: '607f1f77bcf86cd799439013', price: 12 }
];
const chain = makeChain(mockItems);
vi.mocked(PriceRecordModel.find).mockReturnValue(chain as any);
const result = await repo.findByProduct('h1', 'prod1', { limit: 2 });
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(true);
expect(result.pagination.cursor).toBe(Buffer.from('607f1f77bcf86cd799439012').toString('base64'));
});
});
describe('compareStores', () => {
it('runs group/aggregate queries ordered by deviance', async () => {
const mockAggResult = [
{ _id: 's1', storeName: 'Cheap', latestPrice: 10, latestPricePerUnit: 1, currency: 'USD', date: new Date() }
];
vi.mocked(PriceRecordModel.aggregate).mockReturnValue({
exec: vi.fn().mockResolvedValue(mockAggResult)
} as any);
const result = await repo.compareStores('h1', 'p1');
expect(PriceRecordModel.aggregate).toHaveBeenCalled();
expect(result).toHaveLength(1);
expect(result[0].storeId).toBe('s1');
expect(result[0].latestPricePerUnit).toBe(1);
});
});
describe('getLatestForProduct', () => {
it('queries latest pricing document ordered by date descending', async () => {
const chain = makeChain({ _id: 'pr1' });
vi.mocked(PriceRecordModel.findOne).mockReturnValue(chain as any);
await repo.getLatestForProduct('h1', 'p1', 's1');
expect(PriceRecordModel.findOne).toHaveBeenCalledWith({ householdId: 'h1', productId: 'p1', storeId: 's1' });
expect(chain.sort).toHaveBeenCalledWith({ date: -1 });
});
});
describe('getAnalytics', () => {
it('executes Promise.all parallel pipeline aggregations for periods, buckets, categories, and inflation', async () => {
const mockExec = vi.fn().mockResolvedValue([]);
vi.mocked(PriceRecordModel.aggregate).mockReturnValue({
exec: mockExec
} as any);
await repo.getAnalytics('h1');
// 4 explicit pipeline calls should have fired in Promise.all + inflation alert
expect(PriceRecordModel.aggregate).toHaveBeenCalledTimes(4);
});
});
});

View file

@ -0,0 +1,218 @@
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',
realm_access: { roles: ['member'] },
householdIds: ['hh1'],
},
protectedHeader: {},
key: {},
}),
}));
const mockCreate = vi.fn();
const mockCreateMany = vi.fn();
const mockFindByProduct = vi.fn();
const mockCompareStores = vi.fn();
const mockGetAnalytics = vi.fn();
vi.mock('../../../src/modules/prices/prices.repository.js', () => ({
PricesRepository: class {
create = mockCreate;
createMany = mockCreateMany;
findByProduct = mockFindByProduct;
compareStores = mockCompareStores;
getAnalytics = mockGetAnalytics;
},
}));
vi.mock('../../../src/modules/products/products.repository.js', () => ({
ProductsRepository: class {
findById = vi.fn().mockResolvedValue({ name: 'Mock Product' });
findByIds = vi.fn().mockResolvedValue([{ _id: 'p1', name: 'Mock Product' }]);
},
}));
vi.mock('../../../src/modules/stores/stores.repository.js', () => ({
StoresRepository: class {
findById = vi.fn().mockResolvedValue({ name: 'Mock Store' });
},
}));
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 pricesRoutes from '../../../src/modules/prices/prices.routes.js';
describe('prices.routes', () => {
let app: any;
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(pricesRoutes);
await instance.ready();
return instance;
}
const authHeaders = { authorization: 'Bearer valid' };
beforeEach(async () => {
vi.clearAllMocks();
app = await buildTestApp();
});
afterEach(async () => {
if (app) await app.close();
});
function makeRecord(overrides = {}) {
return {
_id: 'r1',
householdId: 'hh1',
productId: 'p1',
productName: 'Apples',
storeId: 's1',
storeName: 'Store',
price: 10,
currency: 'USD',
quantity: 1,
unit: 'piece',
pricePerUnit: 10,
date: new Date(),
createdBy: 'kc-1',
createdAt: new Date(),
...overrides,
};
}
describe('POST /api/v1/households/:householdId/prices', () => {
it('records price and returns 201 response', async () => {
mockCreate.mockResolvedValue(
makeRecord({
receiptImageUrl: 'http://test.com/img.jpg',
notes: 'Custom notes',
date: '2026-05-14T00:00:00.000Z',
})
);
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/prices',
headers: { ...authHeaders, 'content-type': 'application/json' },
body: JSON.stringify({
productId: 'p1',
storeId: 's1',
price: 5.99,
currency: 'USD',
quantity: 1,
unit: 'piece',
}),
});
if (res.statusCode === 500) {
console.log('ERROR PAYLOAD:', res.payload);
}
expect(res.statusCode).toBe(201);
expect(res.json().productName).toBe('Apples');
});
});
describe('GET /api/v1/households/:householdId/prices/history/:productId', () => {
it('returns a paginated envelope of historical pricing data', async () => {
mockFindByProduct.mockResolvedValue({
data: [makeRecord()],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/prices/history/p1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data).toHaveLength(1);
expect(body.pagination.hasMore).toBe(false);
});
});
describe('GET /api/v1/households/:householdId/prices/analytics', () => {
it('returns analytical metrics suite with properly formatted dates', async () => {
mockGetAnalytics.mockResolvedValue({
spendingOverTime: [],
averageBasketByStore: [],
spendingByCategory: [],
priceAlerts: [{ productId: 'p1', productName: 'Bread', storeId: 's1', storeName: 'Store', previousPrice: 2, currentPrice: 2.5, changePercent: 25, date: new Date() }],
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/prices/analytics',
headers: authHeaders,
});
if (res.statusCode === 500) {
console.log('ERROR PAYLOAD:', res.payload);
}
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.priceAlerts).toHaveLength(1);
expect(typeof body.priceAlerts[0].date).toBe('string');
});
});
describe('POST /api/v1/households/:householdId/prices/bulk', () => {
it('records bulk prices and returns 201', async () => {
mockCreateMany.mockResolvedValue([makeRecord()]);
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/prices/bulk',
headers: { ...authHeaders, 'content-type': 'application/json' },
body: JSON.stringify({
storeId: 's1',
items: [{ productId: 'p1', price: 10, quantity: 1, unit: 'piece' }],
}),
});
expect(res.statusCode).toBe(201);
expect(res.json()[0].productName).toBe('Apples');
});
});
describe('GET /api/v1/households/:householdId/prices/compare/:productId', () => {
it('returns comparison array', async () => {
mockCompareStores.mockResolvedValue([{ storeId: 's1', storeName: 'Store', latestPrice: 10, latestPricePerUnit: 10, currency: 'USD', date: new Date() }]);
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/prices/compare/p1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(res.json().data).toHaveLength(1);
});
});
});

View file

@ -0,0 +1,175 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { PricesService } from '../../../src/modules/prices/prices.service.js';
import { NotFoundError } from '../../../src/common/errors.js';
describe('PricesService', () => {
let service: PricesService;
const mockPricesRepo = {
create: vi.fn(),
createMany: vi.fn(),
findByProduct: vi.fn(),
compareStores: vi.fn(),
getAnalytics: vi.fn(),
getLatestForProduct: vi.fn(),
};
const mockProductsRepo = {
findById: vi.fn(),
findByIds: vi.fn(),
};
const mockStoresRepo = {
findById: vi.fn(),
};
beforeEach(() => {
vi.clearAllMocks();
service = new PricesService({
pricesRepository: mockPricesRepo as any,
productsRepository: mockProductsRepo as any,
storesRepository: mockStoresRepo as any,
});
});
describe('recordPrice', () => {
it('calculates unit price and persists data on existing linkages', async () => {
mockProductsRepo.findById.mockResolvedValue({ name: 'Milk' });
mockStoresRepo.findById.mockResolvedValue({ name: 'Target' });
mockPricesRepo.create.mockResolvedValue({ _id: 'rec1' });
const result = await service.recordPrice(
{ productId: 'p1', storeId: 's1', price: 4, quantity: 2, unit: 'ml' as any, currency: 'USD' },
'hh1',
'u1'
);
expect(mockPricesRepo.create).toHaveBeenCalledWith(
expect.objectContaining({
productName: 'Milk',
storeName: 'Target',
pricePerUnit: 2,
})
);
expect(result._id).toBe('rec1');
});
it('handles zero quantity and defaults date to current when recording price', async () => {
mockProductsRepo.findById.mockResolvedValue({ name: 'Bread' });
mockStoresRepo.findById.mockResolvedValue({ name: 'Aldi' });
mockPricesRepo.create.mockImplementation(arg => Promise.resolve({ ...arg, _id: 'rec1' }));
const result = await service.recordPrice(
{ productId: 'p2', storeId: 's2', price: 5, quantity: 0, unit: 'g' as any, currency: 'USD' },
'hh1',
'u1'
);
expect(mockPricesRepo.create).toHaveBeenCalledWith(
expect.objectContaining({
pricePerUnit: 5,
date: expect.any(Date),
})
);
expect(result._id).toBe('rec1');
});
it('throws NotFound if product is invalid', async () => {
mockProductsRepo.findById.mockResolvedValue(null);
await expect(
service.recordPrice(
{ productId: 'p1', storeId: 's1', price: 1, quantity: 1, unit: 'g' as any, currency: 'USD' },
'hh1',
'u1'
)
).rejects.toThrow(NotFoundError);
});
});
describe('recordBulkPrices', () => {
it('ingests multiple mappings throwing notFound if one catalog match fails', async () => {
mockStoresRepo.findById.mockResolvedValue({ name: 'Aldi' });
mockProductsRepo.findByIds.mockResolvedValue([{ _id: 'p1', name: 'Bread' }]);
mockPricesRepo.createMany.mockImplementation(args => args);
const result = await service.recordBulkPrices(
{
storeId: 's1',
items: [{ productId: 'p1', price: 3, quantity: 1, unit: 'g' as any }],
},
'hh1',
'u1'
);
expect(mockPricesRepo.createMany).toHaveBeenCalled();
expect(result).toHaveLength(1);
expect(result[0].productName).toBe('Bread');
});
it('throws NotFoundError if a product is missing from the catalog', async () => {
mockStoresRepo.findById.mockResolvedValue({ name: 'Aldi' });
mockProductsRepo.findByIds.mockResolvedValue([]); // Missing product
await expect(
service.recordBulkPrices(
{ storeId: 's1', items: [{ productId: 'p1', price: 3, quantity: 1, unit: 'g' as any }] },
'hh1',
'u1'
)
).rejects.toThrow(NotFoundError);
});
it('throws NotFoundError if store is missing', async () => {
mockStoresRepo.findById.mockResolvedValue(null);
await expect(
service.recordBulkPrices(
{ storeId: 's1', items: [{ productId: 'p1', price: 3, quantity: 1, unit: 'g' as any }] },
'hh1',
'u1'
)
).rejects.toThrow(NotFoundError);
});
});
describe('Wrappers (getPriceHistory, compareStores, getAnalytics)', () => {
it('delegates to repository correctly', async () => {
mockPricesRepo.findByProduct.mockResolvedValue('history');
mockPricesRepo.compareStores.mockResolvedValue('compare');
mockPricesRepo.getAnalytics.mockResolvedValue('analytics');
expect(await service.getPriceHistory('p1', 'hh1', { page: 1, limit: 10 })).toBe('history');
expect(await service.compareStores('p1', 'hh1')).toBe('compare');
expect(await service.getAnalytics('hh1')).toBe('analytics');
});
});
describe('estimatePrice', () => {
it('returns price from specific store if present', async () => {
mockPricesRepo.getLatestForProduct.mockResolvedValue({ price: 8 });
const val = await service.estimatePrice('prod1', 'hh1', 'storeA');
expect(val).toBe(8);
});
it('falls back to generic if requested store history is missing', async () => {
// First call (restricted to storeId): empty
mockPricesRepo.getLatestForProduct.mockResolvedValueOnce(null);
// Second call (generic): matches
mockPricesRepo.getLatestForProduct.mockResolvedValueOnce({ price: 12 });
const val = await service.estimatePrice('prod1', 'hh1', 'storeA');
expect(mockPricesRepo.getLatestForProduct).toHaveBeenCalledTimes(2);
expect(val).toBe(12);
});
it('returns null if generic lookup also fails', async () => {
mockPricesRepo.getLatestForProduct.mockResolvedValue(null);
const val = await service.estimatePrice('prod1', 'hh1', 'storeA');
expect(val).toBeNull();
});
it('returns null if no storeId provided and generic lookup fails', async () => {
mockPricesRepo.getLatestForProduct.mockResolvedValue(null);
const val = await service.estimatePrice('prod1', 'hh1');
expect(val).toBeNull();
});
});
});