|
| 1 | +import { Test, TestingModule } from '@nestjs/testing'; |
| 2 | +import { TokenBlacklistService } from './token-blacklist.service.js'; |
| 3 | +import { RedisService } from '../../config/redis.module.js'; |
| 4 | + |
| 5 | +describe('TokenBlacklistService', () => { |
| 6 | + let service: TokenBlacklistService; |
| 7 | + |
| 8 | + const mockRedisService = { |
| 9 | + set: jest.fn(), |
| 10 | + exists: jest.fn(), |
| 11 | + }; |
| 12 | + |
| 13 | + beforeEach(async () => { |
| 14 | + const module: TestingModule = await Test.createTestingModule({ |
| 15 | + providers: [ |
| 16 | + TokenBlacklistService, |
| 17 | + { provide: RedisService, useValue: mockRedisService }, |
| 18 | + ], |
| 19 | + }).compile(); |
| 20 | + |
| 21 | + service = module.get<TokenBlacklistService>(TokenBlacklistService); |
| 22 | + }); |
| 23 | + |
| 24 | + afterEach(() => { |
| 25 | + jest.clearAllMocks(); |
| 26 | + }); |
| 27 | + |
| 28 | + describe('blacklist', () => { |
| 29 | + it('should store the jti with the given TTL', async () => { |
| 30 | + await service.blacklist('jti-1', 900); |
| 31 | + expect(mockRedisService.set).toHaveBeenCalledWith('blacklist:jti-1', '1', 900); |
| 32 | + }); |
| 33 | + |
| 34 | + it('should not store anything for a non-positive TTL', async () => { |
| 35 | + await service.blacklist('jti-1', 0); |
| 36 | + expect(mockRedisService.set).not.toHaveBeenCalled(); |
| 37 | + }); |
| 38 | + |
| 39 | + it('should not store anything for an empty jti', async () => { |
| 40 | + await service.blacklist('', 900); |
| 41 | + expect(mockRedisService.set).not.toHaveBeenCalled(); |
| 42 | + }); |
| 43 | + }); |
| 44 | + |
| 45 | + describe('isBlacklisted', () => { |
| 46 | + it('should return true when the key exists', async () => { |
| 47 | + mockRedisService.exists.mockResolvedValue(true); |
| 48 | + const result = await service.isBlacklisted('jti-1'); |
| 49 | + expect(result).toBe(true); |
| 50 | + expect(mockRedisService.exists).toHaveBeenCalledWith('blacklist:jti-1'); |
| 51 | + }); |
| 52 | + |
| 53 | + it('should return false when the key does not exist', async () => { |
| 54 | + mockRedisService.exists.mockResolvedValue(false); |
| 55 | + const result = await service.isBlacklisted('jti-1'); |
| 56 | + expect(result).toBe(false); |
| 57 | + }); |
| 58 | + |
| 59 | + it('should return false for an empty jti without querying Redis', async () => { |
| 60 | + const result = await service.isBlacklisted(''); |
| 61 | + expect(result).toBe(false); |
| 62 | + expect(mockRedisService.exists).not.toHaveBeenCalled(); |
| 63 | + }); |
| 64 | + }); |
| 65 | +}); |
0 commit comments