Skip to content

Commit

Permalink
feat: add basic unit tests for tracker ms
Browse files Browse the repository at this point in the history
  • Loading branch information
orig committed Dec 15, 2023
1 parent 0102ba3 commit 7319141
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
39 changes: 37 additions & 2 deletions apps/tracker/src/stats/stats.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,60 @@
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({
providers: [
StatsService,
{
provide: PrismaService,
useValue: jest.fn(),
useValue: mockPrismaService
},
],
}).compile();

service = module.get<StatsService>(StatsService);
prismaService = module.get<PrismaService>(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();
});
});
});
4 changes: 2 additions & 2 deletions apps/tracker/src/stats/stats.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

Expand Down

0 comments on commit 7319141

Please sign in to comment.