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';
const {
mockFind,
mockFindOne,
mockFindOneAndUpdate,
mockFindOneAndDelete,
mockSave,
mockFindById,
} = vi.hoisted(() => ({
mockFind: vi.fn(),
mockFindOne: vi.fn(),
mockFindOneAndUpdate: vi.fn(),
mockFindOneAndDelete: vi.fn(),
mockSave: vi.fn(),
mockFindById: vi.fn(),
}));
vi.mock('../../../src/schemas/freshness-rule.schema.js', () => {
const chain = () => ({
sort: vi.fn().mockReturnThis(),
limit: vi.fn().mockReturnThis(),
lean: vi.fn().mockReturnThis(),
exec: mockFind,
});
const findOneChain = () => ({
lean: vi.fn().mockReturnThis(),
exec: mockFindOne,
});
const findByIdChain = () => ({
lean: vi.fn().mockReturnThis(),
exec: mockFindById,
});
const updateChain = () => ({
lean: vi.fn().mockReturnThis(),
exec: mockFindOneAndUpdate,
});
const deleteChain = () => ({
exec: mockFindOneAndDelete,
});
class FakeModel {
data: unknown;
constructor(data: unknown) {
this.data = data;
}
save() {
mockSave(this.data);
return Promise.resolve({ toObject: () => this.data });
}
static find = vi.fn(() => chain());
static findOne = vi.fn(() => findOneChain());
static findById = vi.fn(() => findByIdChain());
static findOneAndUpdate = vi.fn(() => updateChain());
static findOneAndDelete = vi.fn(() => deleteChain());
}
return { FreshnessRuleModel: FakeModel };
});
import { FreshnessRulesRepository } from '../../../src/modules/freshness-rules/freshness-rules.repository.js';
describe(FreshnessRulesRepository.name, () => {
let repo: FreshnessRulesRepository;
beforeEach(() => {
vi.clearAllMocks();
repo = new FreshnessRulesRepository();
});
describe('findByHousehold', () => {
it('returns paginated results', async () => {
mockFind.mockResolvedValue([{ _id: { toString: () => 'id1' } }]);
const result = await repo.findByHousehold('hh1', { limit: 50 });
expect(result.data).toHaveLength(1);
expect(result.pagination.hasMore).toBe(false);
});
it('applies category filter', async () => {
mockFind.mockResolvedValue([]);
await repo.findByHousehold('hh1', { category: 'dairy', limit: 50 });
expect(mockFind).toHaveBeenCalled();
});
it('applies storageLocation filter', async () => {
mockFind.mockResolvedValue([]);
await repo.findByHousehold('hh1', { storageLocation: 'fridge', limit: 50 });
expect(mockFind).toHaveBeenCalled();
});
it('applies cursor', async () => {
const cursor = Buffer.from('abc').toString('base64');
mockFind.mockResolvedValue([]);
await repo.findByHousehold('hh1', { cursor, limit: 50 });
expect(mockFind).toHaveBeenCalled();
});
});
describe('findById', () => {
it('returns rule', async () => {
mockFindById.mockResolvedValue({ _id: 'id1' });
const result = await repo.findById('id1');
expect(result).toEqual({ _id: 'id1' });
});
});
describe('findApplicableRule', () => {
it('returns household rule when available', async () => {
const rule = { _id: 'r1', householdId: 'hh1' };
mockFindOne.mockResolvedValueOnce(rule);
const result = await repo.findApplicableRule('hh1', 'dairy', 'fridge');
expect(result).toEqual(rule);
});
it('falls back to system rule', async () => {
const systemRule = { _id: 'r2', householdId: null };
mockFindOne.mockResolvedValueOnce(null).mockResolvedValueOnce(systemRule);
const result = await repo.findApplicableRule('hh1', 'dairy', 'fridge');
expect(result).toEqual(systemRule);
});
it('returns null when no rule found', async () => {
mockFindOne.mockResolvedValue(null);
const result = await repo.findApplicableRule('hh1', 'dairy', 'fridge');
expect(result).toBeNull();
});
});
describe('create', () => {
it('saves and returns rule', async () => {
const data = {
category: 'dairy',
storageLocation: 'fridge',
shelfLifeDays: 14,
openedLifeDays: 7,
};
const result = await repo.create(data);
expect(mockSave).toHaveBeenCalled();
expect(result).toEqual(data);
});
});
describe('update', () => {
it('updates and returns rule', async () => {
mockFindOneAndUpdate.mockResolvedValue({ _id: 'id1' });
const result = await repo.update('id1', 'hh1', { shelfLifeDays: 10 });
expect(result).toEqual({ _id: 'id1' });
});
});
describe('delete', () => {
it('deletes rule', async () => {
mockFindOneAndDelete.mockResolvedValue({ _id: 'id1' });
await repo.delete('id1', 'hh1');
expect(mockFindOneAndDelete).toHaveBeenCalled();
});
});
});

View file

@ -0,0 +1,204 @@
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 { mockFindByHousehold, mockFindById, mockCreate, mockUpdate, mockDelete } = vi.hoisted(
() => ({
mockFindByHousehold: vi.fn(),
mockFindById: vi.fn(),
mockCreate: vi.fn(),
mockUpdate: vi.fn(),
mockDelete: vi.fn(),
}),
);
vi.mock('../../../src/modules/freshness-rules/freshness-rules.repository.js', () => ({
FreshnessRulesRepository: class {
findByHousehold = mockFindByHousehold;
findById = mockFindById;
findApplicableRule = vi.fn();
create = mockCreate;
update = mockUpdate;
delete = mockDelete;
},
}));
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 freshnessRulesRoutes from '../../../src/modules/freshness-rules/freshness-rules.routes.js';
function makeRule(overrides: Record<string, unknown> = {}) {
return {
_id: 'rule-1',
householdId: 'hh1',
category: 'dairy',
storageLocation: 'fridge',
shelfLifeDays: 14,
openedLifeDays: 7,
spoilageSignsToCheck: ['smell'],
source: 'household',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
...overrides,
};
}
describe('freshness-rules.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(freshnessRulesRoutes);
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 /freshness-rules', () => {
it('returns paginated list', async () => {
mockFindByHousehold.mockResolvedValue({
data: [makeRule()],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/freshness-rules',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(res.json().data).toHaveLength(1);
});
});
describe('POST /freshness-rules', () => {
it('creates a rule', async () => {
mockCreate.mockResolvedValue(makeRule());
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/freshness-rules',
headers: { ...authHeaders, 'content-type': 'application/json' },
body: JSON.stringify({
category: 'dairy',
storageLocation: 'fridge',
shelfLifeDays: 14,
openedLifeDays: 7,
}),
});
expect(res.statusCode).toBe(201);
});
it('rejects invalid category', async () => {
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/freshness-rules',
headers: { ...authHeaders, 'content-type': 'application/json' },
body: JSON.stringify({
category: 'invalid',
storageLocation: 'fridge',
shelfLifeDays: 14,
openedLifeDays: 7,
}),
});
expect(res.statusCode).toBe(400);
});
});
describe('PATCH /freshness-rules/:id', () => {
it('updates a rule', async () => {
mockFindById.mockResolvedValue(makeRule());
mockUpdate.mockResolvedValue(makeRule({ shelfLifeDays: 10 }));
const res = await app.inject({
method: 'PATCH',
url: '/api/v1/households/hh1/freshness-rules/rule-1',
headers: { ...authHeaders, 'content-type': 'application/json' },
body: JSON.stringify({ shelfLifeDays: 10 }),
});
expect(res.statusCode).toBe(200);
});
});
describe('PATCH /freshness-rules/:id with optional fields', () => {
it('returns rule with all optional fields', async () => {
mockFindById.mockResolvedValue(makeRule());
mockUpdate.mockResolvedValue(makeRule({ freezerLifeDays: 90, tips: 'Keep sealed' }));
const res = await app.inject({
method: 'PATCH',
url: '/api/v1/households/hh1/freshness-rules/rule-1',
headers: { ...authHeaders, 'content-type': 'application/json' },
body: JSON.stringify({ freezerLifeDays: 90, tips: 'Keep sealed' }),
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.freezerLifeDays).toBe(90);
expect(body.tips).toBe('Keep sealed');
});
});
describe('DELETE /freshness-rules/:id', () => {
it('deletes a rule', async () => {
mockFindById.mockResolvedValue(makeRule());
mockDelete.mockResolvedValue(makeRule());
const res = await app.inject({
method: 'DELETE',
url: '/api/v1/households/hh1/freshness-rules/rule-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(204);
});
});
});

View file

@ -0,0 +1,137 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { FreshnessRulesService } from '../../../src/modules/freshness-rules/freshness-rules.service.js';
import { NotFoundError, BadRequestError } from '../../../src/common/errors.js';
import { FreshnessRuleSource } from '@meshitrack/shared';
const mockRepo = {
findByHousehold: vi.fn(),
findById: vi.fn(),
findApplicableRule: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
};
describe(FreshnessRulesService.name, () => {
let service: FreshnessRulesService;
beforeEach(() => {
vi.clearAllMocks();
service = new FreshnessRulesService({
freshnessRulesRepository: mockRepo 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: 50 });
expect(result).toEqual(expected);
});
});
describe('create', () => {
it('creates household rule', async () => {
const data = {
category: 'dairy' as never,
storageLocation: 'fridge' as never,
shelfLifeDays: 14,
openedLifeDays: 7,
spoilageSignsToCheck: [],
};
mockRepo.create.mockResolvedValue({ ...data, _id: 'r1', householdId: 'hh1' });
const result = await service.create(data, 'hh1');
expect(mockRepo.create).toHaveBeenCalledWith({
...data,
householdId: 'hh1',
source: FreshnessRuleSource.HOUSEHOLD,
});
expect(result).toBeDefined();
});
});
describe('update', () => {
it('updates household rule', async () => {
mockRepo.findById.mockResolvedValue({
_id: 'r1',
householdId: 'hh1',
source: FreshnessRuleSource.HOUSEHOLD,
});
mockRepo.update.mockResolvedValue({ _id: 'r1', shelfLifeDays: 10 });
const result = await service.update('r1', 'hh1', { shelfLifeDays: 10 });
expect(result).toBeDefined();
});
it('throws NotFoundError when rule not found', async () => {
mockRepo.findById.mockResolvedValue(null);
await expect(service.update('missing', 'hh1', {})).rejects.toThrow(NotFoundError);
});
it('throws BadRequestError for system rules', async () => {
mockRepo.findById.mockResolvedValue({
_id: 'r1',
householdId: null,
source: FreshnessRuleSource.SYSTEM,
});
await expect(service.update('r1', 'hh1', {})).rejects.toThrow(BadRequestError);
});
it('throws NotFoundError for another household rule', async () => {
mockRepo.findById.mockResolvedValue({
_id: 'r1',
householdId: 'other-hh',
source: FreshnessRuleSource.HOUSEHOLD,
});
await expect(service.update('r1', 'hh1', {})).rejects.toThrow(NotFoundError);
});
it('throws NotFoundError when update returns null', async () => {
mockRepo.findById.mockResolvedValue({
_id: 'r1',
householdId: 'hh1',
source: FreshnessRuleSource.HOUSEHOLD,
});
mockRepo.update.mockResolvedValue(null);
await expect(service.update('r1', 'hh1', {})).rejects.toThrow(NotFoundError);
});
});
describe('delete', () => {
it('deletes household rule', async () => {
mockRepo.findById.mockResolvedValue({
_id: 'r1',
householdId: 'hh1',
source: FreshnessRuleSource.HOUSEHOLD,
});
mockRepo.delete.mockResolvedValue({ _id: 'r1' });
await service.delete('r1', 'hh1');
expect(mockRepo.delete).toHaveBeenCalledWith('r1', 'hh1');
});
it('throws NotFoundError when rule not found', async () => {
mockRepo.findById.mockResolvedValue(null);
await expect(service.delete('missing', 'hh1')).rejects.toThrow(NotFoundError);
});
it('throws BadRequestError for system rules', async () => {
mockRepo.findById.mockResolvedValue({
_id: 'r1',
householdId: null,
source: FreshnessRuleSource.SYSTEM,
});
await expect(service.delete('r1', 'hh1')).rejects.toThrow(BadRequestError);
});
it('throws NotFoundError for another household rule', async () => {
mockRepo.findById.mockResolvedValue({
_id: 'r1',
householdId: 'other-hh',
source: FreshnessRuleSource.HOUSEHOLD,
});
await expect(service.delete('r1', 'hh1')).rejects.toThrow(NotFoundError);
});
});
});