auth.service.spec.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Test, TestingModule } from '@nestjs/testing';
  2. import { AuthService } from './auth.service';
  3. import { LocalStrategy } from './local.strategy';
  4. import { UsersModule } from '../users/users.module';
  5. import { PassportModule } from '@nestjs/passport';
  6. import { JwtModule } from '@nestjs/jwt';
  7. import { jwtConstants } from './const';
  8. import { JwtStrategy } from './jwt.strategy';
  9. import { HttpStatus } from '@nestjs/common';
  10. describe('AuthService', () => {
  11. let service: AuthService;
  12. let localStrategy: LocalStrategy;
  13. beforeEach(async () => {
  14. const module: TestingModule = await Test.createTestingModule({
  15. imports: [
  16. PassportModule.register({ defaultStrategy: 'jwt' }),
  17. JwtModule.register({
  18. secret: jwtConstants.secret,
  19. signOptions: { expiresIn: '1d' },
  20. }),
  21. UsersModule,
  22. ],
  23. providers: [AuthService, LocalStrategy, JwtStrategy],
  24. }).compile();
  25. service = module.get<AuthService>(AuthService);
  26. localStrategy = module.get<LocalStrategy>(LocalStrategy);
  27. });
  28. it('should be defined', () => {
  29. expect(service).toBeDefined();
  30. });
  31. it('validateUser shoule be true', async () => {
  32. const res = await service.validateUser('milvus', 'milvus-admin');
  33. expect(res).toEqual({ userId: 1, username: 'milvus' });
  34. });
  35. it('validateUser shoule be null', async () => {
  36. const res = await service.validateUser('notexist', '123');
  37. expect(res).toBeNull();
  38. });
  39. it('login', async () => {
  40. const res = await service.login({ username: 'milvus', userId: 1 });
  41. expect(res).toHaveProperty('access_token');
  42. });
  43. it('local validate', async () => {
  44. try {
  45. await localStrategy.validate('notexist', 'asd');
  46. } catch (e) {
  47. expect(e.status).toEqual(HttpStatus.UNAUTHORIZED);
  48. }
  49. });
  50. });