app.e2e-spec.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { Test, TestingModule } from '@nestjs/testing';
  2. import * as request from 'supertest';
  3. import { AppModule } from '../src/app.module';
  4. import { HttpStatus, ValidationPipe } from '@nestjs/common';
  5. describe('App (e2e)', () => {
  6. let app;
  7. let accessTokenJwt: string;
  8. beforeAll(async () => {
  9. const moduleFixture: TestingModule = await Test.createTestingModule({
  10. imports: [AppModule],
  11. })
  12. .compile();
  13. app = moduleFixture.createNestApplication();
  14. app.setGlobalPrefix('api');
  15. app.useGlobalPipes(
  16. new ValidationPipe({
  17. whitelist: true,
  18. transform: true,
  19. forbidNonWhitelisted: true,
  20. transformOptions: {
  21. enableImplicitConversion: true,
  22. },
  23. }),
  24. );
  25. await app.init();
  26. });
  27. describe('AppController (e2e)', () => {
  28. it('should return the follwing message: "This is a simple example of item returned by your APIs." [GET /api]', () => {
  29. return request(app.getHttpServer())
  30. .get('/api')
  31. .expect({
  32. message: 'This is a simple example of item returned by your APIs.',
  33. })
  34. .expect(HttpStatus.OK);
  35. });
  36. describe('should sign in and get a "live" JWT', () => {
  37. it('should authenticates user with valid credentials and provides a jwt token', () => {
  38. return request(app.getHttpServer())
  39. .post('/api/auth/login')
  40. .send({
  41. email: 'test@example.com',
  42. password: 'pass123',
  43. })
  44. .then(({ body }) => {
  45. accessTokenJwt = body.accessToken;
  46. expect(accessTokenJwt).toMatch(
  47. /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/,
  48. );
  49. expect(body).toEqual({
  50. sub: 1,
  51. expiresIn: '3600',
  52. audience: '127.0.0.1:3001',
  53. issuer: '127.0.0.1:3001',
  54. accessToken: accessTokenJwt,
  55. user: { name: 'name #1', email: 'test@example.com', id: 1 },
  56. });
  57. expect(HttpStatus.OK);
  58. });
  59. });
  60. it('should return the follwing message: "Access to protected resources granted! This protected resource is displayed when the token is successfully provided". - ( endpoint protected ) [GET /api/secure]', () => {
  61. return request(app.getHttpServer())
  62. .get('/api/secure')
  63. .set('Authorization', `Bearer ${accessTokenJwt}`)
  64. .expect({
  65. message:
  66. 'Access to protected resources granted! This protected resource is displayed when the token is successfully provided.',
  67. });
  68. });
  69. });
  70. });
  71. afterAll(async () => {
  72. await app.close();
  73. });
  74. });