86 lines
2.6 KiB
TypeScript
86 lines
2.6 KiB
TypeScript
import { describe, it, expect, vi, type Mock } from 'vitest';
|
|
import { RecordPageViewUseCase, type RecordPageViewInput, type RecordPageViewOutput } from './RecordPageViewUseCase';
|
|
import type { IPageViewRepository } from '../../domain/repositories/IPageViewRepository';
|
|
import { PageView } from '../../domain/entities/PageView';
|
|
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
|
|
import type { EntityType, VisitorType } from '../../domain/types/PageView';
|
|
|
|
describe('RecordPageViewUseCase', () => {
|
|
let pageViewRepository: {
|
|
save: Mock;
|
|
};
|
|
let logger: Logger;
|
|
let output: UseCaseOutputPort<RecordPageViewOutput> & { present: Mock };
|
|
let useCase: RecordPageViewUseCase;
|
|
|
|
beforeEach(() => {
|
|
pageViewRepository = {
|
|
save: vi.fn(),
|
|
};
|
|
|
|
logger = {
|
|
debug: vi.fn(),
|
|
info: vi.fn(),
|
|
warn: vi.fn(),
|
|
error: vi.fn(),
|
|
} as unknown as Logger;
|
|
|
|
output = {
|
|
present: vi.fn(),
|
|
};
|
|
|
|
useCase = new RecordPageViewUseCase(
|
|
pageViewRepository as unknown as IPageViewRepository,
|
|
logger,
|
|
output,
|
|
);
|
|
});
|
|
|
|
it('creates and saves a PageView and presents its id', async () => {
|
|
const input: RecordPageViewInput = {
|
|
entityType: 'league' as EntityType,
|
|
entityId: 'league-1',
|
|
visitorId: 'visitor-1',
|
|
visitorType: 'anonymous' as VisitorType,
|
|
sessionId: 'session-1',
|
|
referrer: 'https://example.com',
|
|
userAgent: 'jest',
|
|
country: 'US',
|
|
};
|
|
|
|
pageViewRepository.save.mockResolvedValue(undefined);
|
|
|
|
const result = await useCase.execute(input);
|
|
|
|
expect(result.isOk()).toBe(true);
|
|
expect(pageViewRepository.save).toHaveBeenCalledTimes(1);
|
|
const saved = (pageViewRepository.save as unknown as Mock).mock.calls?.[0]?.[0] as PageView;
|
|
|
|
expect(saved).toBeInstanceOf(PageView);
|
|
expect(saved.id).toBeDefined();
|
|
expect(saved.entityId).toBe(input.entityId);
|
|
expect(saved.entityType).toBe(input.entityType);
|
|
|
|
expect(output.present).toHaveBeenCalledWith({
|
|
pageViewId: saved.id,
|
|
});
|
|
expect((logger.info as unknown as Mock)).toHaveBeenCalled();
|
|
});
|
|
|
|
it('logs and presents error when repository save fails', async () => {
|
|
const input: RecordPageViewInput = {
|
|
entityType: 'league' as EntityType,
|
|
entityId: 'league-1',
|
|
visitorType: 'anonymous' as VisitorType,
|
|
sessionId: 'session-1',
|
|
};
|
|
|
|
const error = new Error('DB error');
|
|
pageViewRepository.save.mockRejectedValue(error);
|
|
|
|
const result = await useCase.execute(input);
|
|
|
|
expect(result.isErr()).toBe(true);
|
|
expect((logger.error as unknown as Mock)).toHaveBeenCalled();
|
|
});
|
|
}); |