|
| 1 | +import { JwtModule } from '@nestjs/jwt' |
| 2 | +import { PassportModule } from '@nestjs/passport' |
| 3 | +import { Test } from '@nestjs/testing' |
| 4 | +import { getModelToken } from 'nestjs-typegoose' |
| 5 | +import { SECURITY } from '~/app.config' |
| 6 | +import { AuthService } from '~/modules/auth/auth.service' |
| 7 | +import { JwtStrategy } from '~/modules/auth/jwt.strategy' |
| 8 | +import { UserModel } from '~/modules/user/user.model' |
| 9 | + |
| 10 | +describe('Test AuthService', () => { |
| 11 | + let service: AuthService |
| 12 | + |
| 13 | + const mockUser = { |
| 14 | + _id: '1', |
| 15 | + id: '1', |
| 16 | + username: 'test-user', |
| 17 | + email: 'tukon@gmail.com', |
| 18 | + authCode: 'authCode', |
| 19 | + } |
| 20 | + beforeAll(async () => { |
| 21 | + const __secret: any = SECURITY.jwtSecret || 'asjhczxiucipoiopiqm2376' |
| 22 | + |
| 23 | + const jwtModule = JwtModule.registerAsync({ |
| 24 | + useFactory() { |
| 25 | + return { |
| 26 | + secret: __secret, |
| 27 | + signOptions: { |
| 28 | + expiresIn: SECURITY.jwtExpire, |
| 29 | + algorithm: 'HS256', |
| 30 | + }, |
| 31 | + } |
| 32 | + }, |
| 33 | + }) |
| 34 | + |
| 35 | + const moduleRef = Test.createTestingModule({ |
| 36 | + imports: [jwtModule, PassportModule], |
| 37 | + providers: [ |
| 38 | + JwtStrategy, |
| 39 | + AuthService, |
| 40 | + { |
| 41 | + provide: getModelToken(UserModel.name), |
| 42 | + useValue: { |
| 43 | + findById: jest.fn().mockReturnValue({ |
| 44 | + select: jest.fn().mockResolvedValue({ |
| 45 | + ...mockUser, |
| 46 | + }), |
| 47 | + }), |
| 48 | + }, |
| 49 | + }, |
| 50 | + ], |
| 51 | + }) |
| 52 | + |
| 53 | + const app = await moduleRef.compile() |
| 54 | + await app.init() |
| 55 | + service = app.get(AuthService) |
| 56 | + }) |
| 57 | + |
| 58 | + it('should sign token', async () => { |
| 59 | + const _token = await service.signToken('1') |
| 60 | + expect(_token).toBeDefined() |
| 61 | + }) |
| 62 | + |
| 63 | + it('should verifyied', async () => { |
| 64 | + const user = await service.verifyPayload({ |
| 65 | + _id: '1', |
| 66 | + authCode: 'authCode', |
| 67 | + }) |
| 68 | + expect(user).toBeDefined() |
| 69 | + expect(user).toEqual(mockUser) |
| 70 | + }) |
| 71 | +}) |
0 commit comments