auth.e2e-spec.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { INestApplication } from '@nestjs/common';
  2. import { JwtService } from '@nestjs/jwt';
  3. import { Test } from '@nestjs/testing';
  4. import * as request from 'supertest';
  5. import { AppModule } from '../src/app.module';
  6. import { configureApp } from '../src/app.setup';
  7. describe('Auth (e2e)', () => {
  8. let app: INestApplication;
  9. let jwtService: JwtService;
  10. beforeAll(async () => {
  11. const moduleRef = await Test.createTestingModule({
  12. imports: [AppModule],
  13. }).compile();
  14. app = moduleRef.createNestApplication();
  15. configureApp(app);
  16. await app.init();
  17. jwtService = app.get(JwtService);
  18. });
  19. afterAll(async () => {
  20. await app.close();
  21. });
  22. it('/api/v1/customers (GET) rejects unauthenticated requests', async () => {
  23. const response = await request(app.getHttpServer())
  24. .get('/api/v1/customers')
  25. .expect(401);
  26. expect(response.body).toEqual({
  27. ok: false,
  28. data: null,
  29. error: {
  30. code: 'AUTH_UNAUTHORIZED',
  31. message: '未登录或登录已失效',
  32. },
  33. });
  34. });
  35. it('/api/v1/auth/stylist/login (POST) returns a token payload with username', async () => {
  36. const response = await request(app.getHttpServer())
  37. .post('/api/v1/auth/stylist/login')
  38. .send({
  39. email: 'stylist@example.com',
  40. password: 'Passw0rd!',
  41. remember: false,
  42. })
  43. .expect(201);
  44. const payload = await jwtService.verifyAsync<{
  45. sub: number;
  46. email: string;
  47. username: string;
  48. }>(response.body.data.token);
  49. expect(payload.sub).toBe(1);
  50. expect(payload.email).toBe('stylist@example.com');
  51. expect(payload.username).toBe('Ogawa');
  52. });
  53. it('/api/v1/customers (GET) accepts a valid signed token', async () => {
  54. const token = await jwtService.signAsync({
  55. sub: 1,
  56. email: 'stylist@example.com',
  57. username: 'Ogawa',
  58. });
  59. const response = await request(app.getHttpServer())
  60. .get('/api/v1/customers')
  61. .set('Authorization', token)
  62. .expect(200);
  63. expect(response.body).toEqual({
  64. ok: true,
  65. data: {
  66. items: [],
  67. total: 0,
  68. page: 1,
  69. pageSize: 20,
  70. },
  71. error: null,
  72. });
  73. });
  74. });