diff --git a/apps/tracker/src/stats/stats.service.spec.ts b/apps/tracker/src/stats/stats.service.spec.ts index 4832916b..5a84a705 100644 --- a/apps/tracker/src/stats/stats.service.spec.ts +++ b/apps/tracker/src/stats/stats.service.spec.ts @@ -1,9 +1,18 @@ import { Test, TestingModule } from '@nestjs/testing'; import { StatsService } from './stats.service'; -import { PrismaService } from '@reduced.to/prisma'; +import { PrismaService, Prisma } from '@reduced.to/prisma'; describe('StatsService', () => { let service: StatsService; + let prismaService: PrismaService; + + const mockPrismaService = { + visit: { + create: jest.fn(), + findFirst: jest.fn(), + }, + }; + beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -11,15 +20,41 @@ describe('StatsService', () => { StatsService, { provide: PrismaService, - useValue: jest.fn(), + useValue: mockPrismaService }, ], }).compile(); service = module.get(StatsService); + prismaService = module.get(PrismaService); }); it('should be defined', () => { expect(service).toBeDefined(); }); + + describe('addVisit', () => { + it('should handle PrismaClientKnownRequestError', async () => { + const error = new Prisma.PrismaClientKnownRequestError('message', {code: 'P2025', meta: {}, clientVersion: 'v1'}); + mockPrismaService.visit.create.mockRejectedValue(error); + await expect(service.addVisit('testKey', { hashedIp: 'testIp', ua: 'testAgent' })).resolves.toBeUndefined(); + }); + + it('should throw an error for unexpected errors', async () => { + mockPrismaService.visit.create.mockRejectedValue(new Error('Unexpected error')); + await expect(service.addVisit('testKey', { hashedIp: 'testIp', ua: 'testAgent' })).rejects.toThrow('Unexpected error'); + }); + }); + + describe('isUniqueVisit', () => { + it('should return true for a unique visit', async () => { + mockPrismaService.visit.findFirst.mockResolvedValue(null); + await expect(service.isUniqueVisit('testKey', 'testIp')).resolves.toBeTruthy(); + }); + + it('should return false for a non-unique visit', async () => { + mockPrismaService.visit.findFirst.mockResolvedValue({ id: 1 }); + await expect(service.isUniqueVisit('testKey', 'testIp')).resolves.toBeFalsy(); + }); + }); }); diff --git a/apps/tracker/src/stats/stats.service.ts b/apps/tracker/src/stats/stats.service.ts index 1958d0fd..2ad2d175 100644 --- a/apps/tracker/src/stats/stats.service.ts +++ b/apps/tracker/src/stats/stats.service.ts @@ -27,9 +27,9 @@ export class StatsService { // Link record does not exist for the given key (might be a visit to a temporary link) return; } - - throw err; } + + throw err; } }