- Backend NestJS con módulos de autenticación, inventario, créditos - Frontend React con dashboard y componentes UI - Base de datos PostgreSQL con migraciones - Tests E2E configurados - Configuración de Docker y deployment Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
187 lines
6.3 KiB
TypeScript
187 lines
6.3 KiB
TypeScript
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
|
import { Test, TestingModule } from '@nestjs/testing';
|
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
import { JwtModule, JwtService } from '@nestjs/jwt';
|
|
import * as request from 'supertest';
|
|
import { DataSource } from 'typeorm';
|
|
import * as bcrypt from 'bcrypt';
|
|
|
|
import { AuthModule } from '../src/modules/auth/auth.module';
|
|
import { UsersModule } from '../src/modules/users/users.module';
|
|
import { CreditsModule } from '../src/modules/credits/credits.module';
|
|
import { User } from '../src/modules/users/entities/user.entity';
|
|
import { Otp } from '../src/modules/auth/entities/otp.entity';
|
|
import { RefreshToken } from '../src/modules/auth/entities/refresh-token.entity';
|
|
import { CreditBalance } from '../src/modules/credits/entities/credit-balance.entity';
|
|
import { CreditTransaction } from '../src/modules/credits/entities/credit-transaction.entity';
|
|
import { CreditPackage } from '../src/modules/credits/entities/credit-package.entity';
|
|
|
|
describe('UsersController (e2e)', () => {
|
|
let app: INestApplication;
|
|
let dataSource: DataSource;
|
|
let jwtService: JwtService;
|
|
let accessToken: string;
|
|
let userId: string;
|
|
|
|
beforeAll(async () => {
|
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
|
imports: [
|
|
ConfigModule.forRoot({
|
|
isGlobal: true,
|
|
}),
|
|
TypeOrmModule.forRootAsync({
|
|
imports: [ConfigModule],
|
|
useFactory: () => ({
|
|
type: 'postgres',
|
|
host: process.env.DATABASE_HOST || 'localhost',
|
|
port: parseInt(process.env.DATABASE_PORT || '5433'),
|
|
username: process.env.DATABASE_USER || 'postgres',
|
|
password: process.env.DATABASE_PASSWORD || 'postgres',
|
|
database: process.env.DATABASE_NAME || 'miinventario_test',
|
|
entities: [User, Otp, RefreshToken, CreditBalance, CreditTransaction, CreditPackage],
|
|
synchronize: true,
|
|
dropSchema: true,
|
|
}),
|
|
inject: [ConfigService],
|
|
}),
|
|
JwtModule.register({
|
|
secret: 'test-secret',
|
|
signOptions: { expiresIn: '15m' },
|
|
}),
|
|
AuthModule,
|
|
UsersModule,
|
|
CreditsModule,
|
|
],
|
|
})
|
|
.overrideProvider(ConfigService)
|
|
.useValue({
|
|
get: (key: string, defaultValue?: any) => {
|
|
const config: Record<string, any> = {
|
|
NODE_ENV: 'development',
|
|
DATABASE_HOST: process.env.DATABASE_HOST || 'localhost',
|
|
DATABASE_PORT: parseInt(process.env.DATABASE_PORT || '5433'),
|
|
DATABASE_NAME: process.env.DATABASE_NAME || 'miinventario_test',
|
|
DATABASE_USER: process.env.DATABASE_USER || 'postgres',
|
|
DATABASE_PASSWORD: process.env.DATABASE_PASSWORD || 'postgres',
|
|
JWT_SECRET: 'test-secret',
|
|
JWT_EXPIRES_IN: '15m',
|
|
JWT_REFRESH_SECRET: 'test-refresh-secret',
|
|
JWT_REFRESH_EXPIRES_IN: '7d',
|
|
};
|
|
return config[key] ?? defaultValue;
|
|
},
|
|
})
|
|
.compile();
|
|
|
|
app = moduleFixture.createNestApplication();
|
|
app.useGlobalPipes(
|
|
new ValidationPipe({
|
|
whitelist: true,
|
|
forbidNonWhitelisted: true,
|
|
transform: true,
|
|
}),
|
|
);
|
|
|
|
await app.init();
|
|
dataSource = moduleFixture.get<DataSource>(DataSource);
|
|
jwtService = moduleFixture.get<JwtService>(JwtService);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
if (dataSource?.isInitialized) {
|
|
await dataSource.destroy();
|
|
}
|
|
await app.close();
|
|
});
|
|
|
|
beforeEach(async () => {
|
|
// Clean up and create test user
|
|
await dataSource.query('DELETE FROM refresh_tokens');
|
|
await dataSource.query('DELETE FROM otps');
|
|
await dataSource.query('DELETE FROM credit_transactions');
|
|
await dataSource.query('DELETE FROM credit_balances');
|
|
await dataSource.query('DELETE FROM users');
|
|
|
|
// Create test user
|
|
const passwordHash = await bcrypt.hash('testpassword123', 10);
|
|
const result = await dataSource.query(
|
|
`INSERT INTO users (id, phone, name, "passwordHash", role, "isActive")
|
|
VALUES (uuid_generate_v4(), '5512345678', 'Test User', $1, 'USER', true)
|
|
RETURNING id`,
|
|
[passwordHash],
|
|
);
|
|
userId = result[0].id;
|
|
|
|
// Create credit balance
|
|
await dataSource.query(
|
|
`INSERT INTO credit_balances (id, "userId", balance, "totalPurchased", "totalConsumed", "totalFromReferrals")
|
|
VALUES (uuid_generate_v4(), $1, 100, 100, 0, 0)`,
|
|
[userId],
|
|
);
|
|
|
|
// Generate token
|
|
accessToken = jwtService.sign({ sub: userId });
|
|
});
|
|
|
|
describe('GET /users/me', () => {
|
|
it('should return current user profile', async () => {
|
|
const response = await request(app.getHttpServer())
|
|
.get('/users/me')
|
|
.set('Authorization', `Bearer ${accessToken}`)
|
|
.expect(200);
|
|
|
|
expect(response.body).toMatchObject({
|
|
id: userId,
|
|
name: 'Test User',
|
|
phone: '5512345678',
|
|
});
|
|
});
|
|
|
|
it('should fail without authentication', async () => {
|
|
await request(app.getHttpServer())
|
|
.get('/users/me')
|
|
.expect(401);
|
|
});
|
|
|
|
it('should fail with invalid token', async () => {
|
|
await request(app.getHttpServer())
|
|
.get('/users/me')
|
|
.set('Authorization', 'Bearer invalid-token')
|
|
.expect(401);
|
|
});
|
|
});
|
|
|
|
describe('PATCH /users/me', () => {
|
|
it('should update user profile', async () => {
|
|
const response = await request(app.getHttpServer())
|
|
.patch('/users/me')
|
|
.set('Authorization', `Bearer ${accessToken}`)
|
|
.send({ name: 'Updated Name', businessName: 'Mi Negocio' })
|
|
.expect(200);
|
|
|
|
expect(response.body.name).toBe('Updated Name');
|
|
expect(response.body.businessName).toBe('Mi Negocio');
|
|
});
|
|
|
|
it('should fail without authentication', async () => {
|
|
await request(app.getHttpServer())
|
|
.patch('/users/me')
|
|
.send({ name: 'Updated Name' })
|
|
.expect(401);
|
|
});
|
|
});
|
|
|
|
describe('PATCH /users/me/fcm-token', () => {
|
|
it('should update FCM token', async () => {
|
|
const response = await request(app.getHttpServer())
|
|
.patch('/users/me/fcm-token')
|
|
.set('Authorization', `Bearer ${accessToken}`)
|
|
.send({ fcmToken: 'fcm-token-123' })
|
|
.expect(200);
|
|
|
|
expect(response.body.success).toBe(true);
|
|
});
|
|
});
|
|
});
|