183 lines
5.3 KiB
TypeScript
183 lines
5.3 KiB
TypeScript
|
|
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('./prices.repository.js', () => ({
|
||
|
|
PricesRepository: class {
|
||
|
|
create = mockCreate;
|
||
|
|
createMany = mockCreateMany;
|
||
|
|
findByProduct = mockFindByProduct;
|
||
|
|
compareStores = mockCompareStores;
|
||
|
|
getAnalytics = mockGetAnalytics;
|
||
|
|
},
|
||
|
|
}));
|
||
|
|
|
||
|
|
vi.mock('../products/products.repository.js', () => ({
|
||
|
|
ProductsRepository: class {
|
||
|
|
findById = vi.fn().mockResolvedValue({ name: 'Mock Product' });
|
||
|
|
findByIds = vi.fn().mockResolvedValue([{ _id: 'p1', name: 'Mock Product' }]);
|
||
|
|
},
|
||
|
|
}));
|
||
|
|
|
||
|
|
vi.mock('../stores/stores.repository.js', () => ({
|
||
|
|
StoresRepository: class {
|
||
|
|
findById = vi.fn().mockResolvedValue({ name: 'Mock Store' });
|
||
|
|
},
|
||
|
|
}));
|
||
|
|
|
||
|
|
vi.mock('../users/users.repository.js', () => ({
|
||
|
|
UsersRepository: class {
|
||
|
|
findByKeycloakId = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
|
||
|
|
upsertFromToken = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
|
||
|
|
},
|
||
|
|
}));
|
||
|
|
|
||
|
|
import authPlugin from '../../plugins/auth.plugin.js';
|
||
|
|
import householdPlugin from '../../plugins/household.plugin.js';
|
||
|
|
import usersRoutes from '../users/users.routes.js';
|
||
|
|
import pricesRoutes from './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());
|
||
|
|
|
||
|
|
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');
|
||
|
|
});
|
||
|
|
});
|
||
|
|
});
|