|
| 1 | +import { ConfigModule, ConfigService } from '@nestjs/config'; |
| 2 | +import { Test, type TestingModule } from '@nestjs/testing'; |
| 3 | +import { type Logger } from '@nestjs/common'; |
| 4 | +import { createMock } from '@golevelup/ts-jest'; |
| 5 | +import { verify } from 'jsonwebtoken'; |
| 6 | +import { CelloReferralService } from './cello-referral.service'; |
| 7 | + |
| 8 | +describe('CelloReferralService', () => { |
| 9 | + let service: CelloReferralService; |
| 10 | + |
| 11 | + const celloConfig = { |
| 12 | + 'cello.productId': 'test-product-id', |
| 13 | + 'cello.productSecret': 'test-product-secret', |
| 14 | + }; |
| 15 | + |
| 16 | + beforeEach(async () => { |
| 17 | + const module: TestingModule = await Test.createTestingModule({ |
| 18 | + imports: [ConfigModule], |
| 19 | + providers: [CelloReferralService], |
| 20 | + }) |
| 21 | + .setLogger(createMock<Logger>()) |
| 22 | + .compile(); |
| 23 | + |
| 24 | + service = module.get<CelloReferralService>(CelloReferralService); |
| 25 | + |
| 26 | + const configService = module.get<ConfigService>(ConfigService); |
| 27 | + jest |
| 28 | + .spyOn(configService, 'get') |
| 29 | + .mockImplementation((key: string) => celloConfig[key]); |
| 30 | + }); |
| 31 | + |
| 32 | + afterEach(() => { |
| 33 | + jest.clearAllMocks(); |
| 34 | + jest.restoreAllMocks(); |
| 35 | + }); |
| 36 | + |
| 37 | + describe('generateToken', () => { |
| 38 | + it('When called, then it returns a valid JWT signed with HS512', () => { |
| 39 | + const signupDate = new Date('2024-01-15T10:00:00.000Z'); |
| 40 | + const token = service.generateToken('user-uuid', signupDate); |
| 41 | + |
| 42 | + const decoded = verify(token, celloConfig['cello.productSecret'], { |
| 43 | + algorithms: ['HS512'], |
| 44 | + }) as Record<string, unknown>; |
| 45 | + |
| 46 | + expect(decoded.productId).toBe(celloConfig['cello.productId']); |
| 47 | + expect(decoded.productUserId).toBe('user-uuid'); |
| 48 | + expect(decoded.signupDate).toBe('2024-01-15T10:00:00.000Z'); |
| 49 | + expect(decoded.iat).toBeDefined(); |
| 50 | + expect(decoded.exp).toBe((decoded.iat as number) + 3600); |
| 51 | + }); |
| 52 | + }); |
| 53 | +}); |
0 commit comments