Tests refactor
This commit is contained in:
parent
245520fb50
commit
99134d8556
165 changed files with 911 additions and 531 deletions
|
|
@ -0,0 +1,109 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { NutritionTargetRepository } from '../../../src/modules/nutrition-targets/nutrition-target.repository.js';
|
||||
|
||||
const { mockSave, MockTargetModel } = 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(),
|
||||
updateMany: vi.fn(),
|
||||
});
|
||||
return { mockSave, MockTargetModel: MockModel };
|
||||
});
|
||||
|
||||
vi.mock('../../../src/schemas/nutrition-target.schema.js', () => ({
|
||||
NutritionTargetModel: MockTargetModel,
|
||||
}));
|
||||
|
||||
const { NutritionTargetModel } = await import('../../../src/schemas/nutrition-target.schema.js');
|
||||
|
||||
function makeChain(result: unknown = null) {
|
||||
return {
|
||||
sort: vi.fn().mockReturnThis(),
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: vi.fn().mockResolvedValue(result),
|
||||
};
|
||||
}
|
||||
|
||||
describe(NutritionTargetRepository.name, () => {
|
||||
let repo: NutritionTargetRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new NutritionTargetRepository();
|
||||
});
|
||||
|
||||
describe('findByUser', () => {
|
||||
it('queries by userId, householdId, and isActive: true', async () => {
|
||||
const mockTarget = { _id: 't1', dailyCalories: 2000 };
|
||||
vi.mocked(NutritionTargetModel.findOne).mockReturnValue(makeChain(mockTarget) as never);
|
||||
|
||||
const result = await repo.findByUser('user1', 'hh1');
|
||||
expect(NutritionTargetModel.findOne).toHaveBeenCalledWith({
|
||||
userId: 'user1',
|
||||
householdId: 'hh1',
|
||||
isActive: true,
|
||||
});
|
||||
expect(result).toEqual(mockTarget);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findAllByUser', () => {
|
||||
it('returns all targets sorted by newest first', async () => {
|
||||
const chain = makeChain([]);
|
||||
vi.mocked(NutritionTargetModel.find).mockReturnValue(chain as never);
|
||||
|
||||
await repo.findAllByUser('user1', 'hh1');
|
||||
expect(NutritionTargetModel.find).toHaveBeenCalledWith({
|
||||
userId: 'user1',
|
||||
householdId: 'hh1',
|
||||
});
|
||||
expect(chain.sort).toHaveBeenCalledWith({ createdAt: -1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('saves and returns new document', async () => {
|
||||
const plainDoc = { _id: 'new-id', dailyCalories: 2000 };
|
||||
mockSave.mockResolvedValue({ toObject: () => plainDoc });
|
||||
|
||||
const result = await repo.create({ dailyCalories: 2000 });
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
expect(result).toEqual(plainDoc);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deactivateAllForUser', () => {
|
||||
it('updates all active targets for the user to inactive', async () => {
|
||||
vi.mocked(NutritionTargetModel.updateMany).mockReturnValue({
|
||||
exec: vi.fn().mockResolvedValue({ modifiedCount: 1 }),
|
||||
} as never);
|
||||
|
||||
await repo.deactivateAllForUser('user1', 'hh1');
|
||||
expect(NutritionTargetModel.updateMany).toHaveBeenCalledWith(
|
||||
{ userId: 'user1', householdId: 'hh1', isActive: true },
|
||||
{ $set: { isActive: false } },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('updates specific target using findOneAndUpdate', async () => {
|
||||
const updatedDoc = { _id: 't1', dailyCalories: 2100 };
|
||||
vi.mocked(NutritionTargetModel.findOneAndUpdate).mockReturnValue(makeChain(updatedDoc) as never);
|
||||
|
||||
const result = await repo.update('t1', 'user1', 'hh1', { dailyCalories: 2100 });
|
||||
expect(NutritionTargetModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ _id: 't1', userId: 'user1', householdId: 'hh1' },
|
||||
{ $set: { dailyCalories: 2100 } },
|
||||
{ new: true, lean: true }
|
||||
);
|
||||
expect(result).toEqual(updatedDoc);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,201 @@
|
|||
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 {
|
||||
mockFindByUser,
|
||||
mockFindAllByUser,
|
||||
mockDeactivateAllForUser,
|
||||
mockCreate,
|
||||
} = vi.hoisted(() => ({
|
||||
mockFindByUser: vi.fn(),
|
||||
mockFindAllByUser: vi.fn(),
|
||||
mockDeactivateAllForUser: vi.fn(),
|
||||
mockCreate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/nutrition-targets/nutrition-target.repository.js', () => ({
|
||||
NutritionTargetRepository: class {
|
||||
findByUser = mockFindByUser;
|
||||
findAllByUser = mockFindAllByUser;
|
||||
deactivateAllForUser = mockDeactivateAllForUser;
|
||||
create = mockCreate;
|
||||
},
|
||||
}));
|
||||
|
||||
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 nutritionTargetRoutes from '../../../src/modules/nutrition-targets/nutrition-target.routes.js';
|
||||
|
||||
function makeTarget(overrides = {}) {
|
||||
return {
|
||||
_id: 'target-1',
|
||||
userId: 'kc-1',
|
||||
householdId: 'hh1',
|
||||
dailyCalories: 2000,
|
||||
proteinG: 150,
|
||||
carbsG: 200,
|
||||
fatG: 67,
|
||||
isActive: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('nutrition-target.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(nutritionTargetRoutes);
|
||||
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/nutrition-targets', () => {
|
||||
it('returns the active target if found', async () => {
|
||||
mockFindByUser.mockResolvedValue(makeTarget());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/nutrition-targets',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.dailyCalories).toBe(2000);
|
||||
expect(body.isActive).toBe(true);
|
||||
});
|
||||
|
||||
it('returns a message object if no target is set', async () => {
|
||||
mockFindByUser.mockResolvedValue(null);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/nutrition-targets',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().message).toBe('No active targets defined');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/nutrition-targets/history', () => {
|
||||
it('returns historical targets with optional fields and object _id', async () => {
|
||||
mockFindAllByUser.mockResolvedValue([
|
||||
makeTarget({
|
||||
_id: { toString: () => 'target-1' },
|
||||
isActive: false,
|
||||
fiberG: 30,
|
||||
sugarG: 50,
|
||||
sodiumMg: 2000,
|
||||
createdAt: new Date(),
|
||||
}),
|
||||
makeTarget()
|
||||
]);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/nutrition-targets/history',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body).toHaveLength(2);
|
||||
expect(body[0].fiberG).toBe(30);
|
||||
expect(body[0]._id).toBe('target-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/nutrition-targets', () => {
|
||||
it('creates target and returns it', async () => {
|
||||
mockCreate.mockImplementation((data) => Promise.resolve({ ...data, _id: 'new-id', createdAt: new Date(), updatedAt: new Date() }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/nutrition-targets',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
dailyCalories: 1800,
|
||||
proteinG: 135,
|
||||
carbsG: 180,
|
||||
fatG: 60,
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body.dailyCalories).toBe(1800);
|
||||
expect(body.isActive).toBe(true); // auto activated
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/nutrition-targets/presets', () => {
|
||||
it('returns calculated splits', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/nutrition-targets/presets',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
calories: 2000,
|
||||
strategy: 'loss',
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
// Loss is 40% protein (200g), 30% carbs (150g), 30% fat (67g)
|
||||
expect(body.dailyCalories).toBe(2000);
|
||||
expect(body.proteinG).toBe(200);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { NutritionTargetService } from '../../../src/modules/nutrition-targets/nutrition-target.service.js';
|
||||
import type { NutritionTargetRepository } from '../../../src/modules/nutrition-targets/nutrition-target.repository.js';
|
||||
|
||||
describe(NutritionTargetService.name, () => {
|
||||
let service: NutritionTargetService;
|
||||
let mockRepo: { [K in keyof NutritionTargetRepository]: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
mockRepo = {
|
||||
findByUser: vi.fn(),
|
||||
findAllByUser: vi.fn(),
|
||||
create: vi.fn(),
|
||||
deactivateAllForUser: vi.fn(),
|
||||
update: vi.fn(),
|
||||
} as never;
|
||||
|
||||
service = new NutritionTargetService({
|
||||
nutritionTargetRepository: mockRepo as unknown as NutritionTargetRepository,
|
||||
});
|
||||
});
|
||||
|
||||
describe('getActiveByUser', () => {
|
||||
it('delegates to repository', async () => {
|
||||
const mockTarget = { dailyCalories: 2000, isActive: true };
|
||||
mockRepo.findByUser.mockResolvedValue(mockTarget);
|
||||
|
||||
const result = await service.getActiveByUser('u1', 'h1');
|
||||
expect(mockRepo.findByUser).toHaveBeenCalledWith('u1', 'h1');
|
||||
expect(result).toEqual(mockTarget);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAllByUser', () => {
|
||||
it('delegates to repository', async () => {
|
||||
const mockTargets = [{ dailyCalories: 2000 }, { dailyCalories: 1800 }];
|
||||
mockRepo.findAllByUser.mockResolvedValue(mockTargets);
|
||||
|
||||
const result = await service.getAllByUser('u1', 'h1');
|
||||
expect(mockRepo.findAllByUser).toHaveBeenCalledWith('u1', 'h1');
|
||||
expect(result).toEqual(mockTargets);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setTarget', () => {
|
||||
it('deactivates existing targets before creating an active one', async () => {
|
||||
const mockInput = { dailyCalories: 2000, proteinG: 100, carbsG: 200, fatG: 50, isActive: true };
|
||||
const createdTarget = { ...mockInput, _id: 'new-id', userId: 'u1', householdId: 'h1' };
|
||||
mockRepo.create.mockResolvedValue(createdTarget);
|
||||
|
||||
const result = await service.setTarget('u1', 'h1', mockInput);
|
||||
|
||||
expect(mockRepo.deactivateAllForUser).toHaveBeenCalledWith('u1', 'h1');
|
||||
expect(mockRepo.create).toHaveBeenCalledWith({
|
||||
...mockInput,
|
||||
userId: 'u1',
|
||||
householdId: 'h1',
|
||||
});
|
||||
expect(result).toEqual(createdTarget);
|
||||
});
|
||||
|
||||
it('does NOT deactivate others if isActive is explicitly false', async () => {
|
||||
const mockInput = { dailyCalories: 2000, proteinG: 100, carbsG: 200, fatG: 50, isActive: false };
|
||||
await service.setTarget('u1', 'h1', mockInput);
|
||||
|
||||
expect(mockRepo.deactivateAllForUser).not.toHaveBeenCalled();
|
||||
expect(mockRepo.create).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('calculatePreset', () => {
|
||||
it('calculates macros correctly for maintenance (30p / 40c / 30f)', () => {
|
||||
const result = service.calculatePreset(2000, 'maintenance');
|
||||
|
||||
// Math:
|
||||
// Protein: (2000 * 0.3) / 4 = 600 / 4 = 150
|
||||
// Carbs: (2000 * 0.4) / 4 = 800 / 4 = 200
|
||||
// Fat: (2000 * 0.3) / 9 = 600 / 9 = 66.66 => 67
|
||||
expect(result).toEqual({
|
||||
dailyCalories: 2000,
|
||||
proteinG: 150,
|
||||
carbsG: 200,
|
||||
fatG: 67,
|
||||
isActive: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('calculates macros correctly for loss (40p / 30c / 30f)', () => {
|
||||
const result = service.calculatePreset(2000, 'loss');
|
||||
|
||||
// Math:
|
||||
// Protein: (2000 * 0.4) / 4 = 800 / 4 = 200
|
||||
// Carbs: (2000 * 0.3) / 4 = 600 / 4 = 150
|
||||
// Fat: (2000 * 0.3) / 9 = 600 / 9 = 66.66 => 67
|
||||
expect(result).toEqual({
|
||||
dailyCalories: 2000,
|
||||
proteinG: 200,
|
||||
carbsG: 150,
|
||||
fatG: 67,
|
||||
isActive: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('calculates macros correctly for gain (25p / 50c / 25f)', () => {
|
||||
const result = service.calculatePreset(2000, 'gain');
|
||||
|
||||
// Math:
|
||||
// Protein: (2000 * 0.25) / 4 = 500 / 4 = 125
|
||||
// Carbs: (2000 * 0.5) / 4 = 1000 / 4 = 250
|
||||
// Fat: (2000 * 0.25) / 9 = 500 / 9 = 55.55 => 56
|
||||
expect(result).toEqual({
|
||||
dailyCalories: 2000,
|
||||
proteinG: 125,
|
||||
carbsG: 250,
|
||||
fatG: 56,
|
||||
isActive: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue