feat(product-detail): implement resolver for product details and update component logic for improved error handling
feat(product-carousel): enhance image loading with optimized attributes and improve layout consistency style: refactor HTML structure for better readability and maintainability test(product-detail): add unit tests for product detail resolver and component behavior
This commit is contained in:
parent
6c00a3e2bb
commit
993aa5823a
|
|
@ -1,5 +1,9 @@
|
||||||
import { HttpRequest, provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
|
import { HttpRequest, provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
|
||||||
import { ApplicationConfig, provideAppInitializer, provideBrowserGlobalErrorListeners } from '@angular/core';
|
import {
|
||||||
|
ApplicationConfig,
|
||||||
|
provideAppInitializer,
|
||||||
|
provideBrowserGlobalErrorListeners,
|
||||||
|
} from '@angular/core';
|
||||||
import { provideRouter } from '@angular/router';
|
import { provideRouter } from '@angular/router';
|
||||||
import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
|
import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
|
||||||
|
|
||||||
|
|
@ -8,10 +12,10 @@ import { authBootstrap } from './core/services/auth/auth-bootstrap';
|
||||||
import { authInterceptor } from './core/services/auth/auth.interceptor';
|
import { authInterceptor } from './core/services/auth/auth.interceptor';
|
||||||
import { tenantBootstrap } from './core/services/tenant-bootstrap';
|
import { tenantBootstrap } from './core/services/tenant-bootstrap';
|
||||||
|
|
||||||
function isStoreHomeProductsRequest(request: HttpRequest<unknown>): boolean {
|
function isStoreCatalogRequest(request: HttpRequest<unknown>): boolean {
|
||||||
return (
|
return (
|
||||||
request.method === 'GET' &&
|
request.method === 'GET' &&
|
||||||
/\/api\/tenants\/[^/]+\/productos(?:\?|$)/.test(request.urlWithParams)
|
/\/api\/tenants\/[^/]+\/productos(?:\/\d+)?(?:\?|$)/.test(request.urlWithParams)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -22,11 +26,11 @@ export const appConfig: ApplicationConfig = {
|
||||||
provideClientHydration(
|
provideClientHydration(
|
||||||
withHttpTransferCacheOptions({
|
withHttpTransferCacheOptions({
|
||||||
includeRequestsWithAuthHeaders: true,
|
includeRequestsWithAuthHeaders: true,
|
||||||
filter: isStoreHomeProductsRequest
|
filter: isStoreCatalogRequest,
|
||||||
})
|
}),
|
||||||
),
|
),
|
||||||
provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
|
provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
|
||||||
provideAppInitializer(authBootstrap),
|
provideAppInitializer(authBootstrap),
|
||||||
provideAppInitializer(tenantBootstrap)
|
provideAppInitializer(tenantBootstrap),
|
||||||
]
|
],
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,51 +1,70 @@
|
||||||
<div class="product-carousel d-flex flex-column gap-4">
|
<div class="product-carousel d-flex flex-column gap-4">
|
||||||
<!-- Active/Main Image Area -->
|
<!-- Active/Main Image Area -->
|
||||||
<div class="product-carousel__main position-relative bg-light overflow-hidden">
|
<div class="product-carousel__main position-relative bg-light overflow-hidden">
|
||||||
<!-- Main Image -->
|
<!-- Main Image -->
|
||||||
@if (images().length > 0) {
|
@if (images().length > 0) {
|
||||||
<img [src]="images()[activeIndex()]" alt="Product active image"
|
<img
|
||||||
class="product-carousel__main-image w-100 h-100 object-fit-cover" />
|
[ngSrc]="images()[activeIndex()]"
|
||||||
|
alt="Product active image"
|
||||||
|
fill
|
||||||
|
priority
|
||||||
|
sizes="(min-width: 992px) 42vw, 100vw"
|
||||||
|
class="product-carousel__main-image w-100 h-100 object-fit-cover"
|
||||||
|
/>
|
||||||
} @else {
|
} @else {
|
||||||
<!-- Placeholder -->
|
<!-- Placeholder -->
|
||||||
<div class="product-carousel__placeholder w-100 h-100 d-flex align-items-center justify-content-center text-muted">
|
<div
|
||||||
<i class="fa-solid fa-image fa-3x"></i>
|
class="product-carousel__placeholder w-100 h-100 d-flex align-items-center justify-content-center text-muted"
|
||||||
</div>
|
>
|
||||||
|
<i class="fa-solid fa-image fa-3x"></i>
|
||||||
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
<!-- Discount Badge -->
|
<!-- Discount Badge -->
|
||||||
@if (discount() && discount()! > 0) {
|
@if (discount() && discount()! > 0) {
|
||||||
<span
|
<span
|
||||||
class="product-carousel__discount-badge position-absolute top-0 end-0 bg-primary text-white px-3 py-2 fw-semibold">
|
class="product-carousel__discount-badge position-absolute top-0 end-0 bg-primary text-white px-3 py-2 fw-semibold"
|
||||||
-{{ discount() }}%
|
>
|
||||||
</span>
|
-{{ discount() }}%
|
||||||
|
</span>
|
||||||
}
|
}
|
||||||
|
|
||||||
<!-- Navigation Arrows -->
|
<!-- Navigation Arrows -->
|
||||||
@if (images().length > 1) {
|
@if (images().length > 1) {
|
||||||
<button type="button"
|
<button
|
||||||
class="product-carousel__nav-btn product-carousel__nav-btn--prev position-absolute top-50 translate-middle-y border-0 p-0 d-flex align-items-center justify-content-center"
|
type="button"
|
||||||
(click)="prevImage()" aria-label="Previous image">
|
class="product-carousel__nav-btn product-carousel__nav-btn--prev position-absolute top-50 translate-middle-y border-0 p-0 d-flex align-items-center justify-content-center"
|
||||||
<i class="fa-solid fa-chevron-left"></i>
|
(click)="prevImage()"
|
||||||
</button>
|
aria-label="Previous image"
|
||||||
|
>
|
||||||
|
<i class="fa-solid fa-chevron-left"></i>
|
||||||
|
</button>
|
||||||
|
|
||||||
<button type="button"
|
<button
|
||||||
class="product-carousel__nav-btn product-carousel__nav-btn--next position-absolute top-50 translate-middle-y border-0 p-0 d-flex align-items-center justify-content-center"
|
type="button"
|
||||||
(click)="nextImage()" aria-label="Next image">
|
class="product-carousel__nav-btn product-carousel__nav-btn--next position-absolute top-50 translate-middle-y border-0 p-0 d-flex align-items-center justify-content-center"
|
||||||
<i class="fa-solid fa-chevron-right"></i>
|
(click)="nextImage()"
|
||||||
</button>
|
aria-label="Next image"
|
||||||
|
>
|
||||||
|
<i class="fa-solid fa-chevron-right"></i>
|
||||||
|
</button>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Thumbnails Row -->
|
<!-- Thumbnails Row -->
|
||||||
@if (images().length > 1) {
|
@if (images().length > 1) {
|
||||||
<div class="product-carousel__thumbnails">
|
<div class="product-carousel__thumbnails">
|
||||||
@for (image of images(); track image; let idx = $index) {
|
@for (image of images(); track image; let idx = $index) {
|
||||||
<button type="button" class="product-carousel__thumbnail border-0 p-0 overflow-hidden bg-light"
|
<button
|
||||||
[class.product-carousel__thumbnail--active]="idx === activeIndex()" (click)="selectImage(idx)"
|
type="button"
|
||||||
[attr.aria-label]="'Select image ' + (idx + 1)">
|
class="product-carousel__thumbnail border-0 p-0 overflow-hidden bg-light"
|
||||||
<img [src]="image" alt="Product thumbnail" class="w-100 h-100 object-fit-cover" />
|
[class.product-carousel__thumbnail--active]="idx === activeIndex()"
|
||||||
</button>
|
(click)="selectImage(idx)"
|
||||||
}
|
[attr.aria-label]="'Select image ' + (idx + 1)"
|
||||||
</div>
|
>
|
||||||
|
<img [src]="image" alt="Product thumbnail" class="w-100 h-100 object-fit-cover" />
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,13 @@
|
||||||
import { ChangeDetectionStrategy, Component, input, signal } from '@angular/core';
|
import { ChangeDetectionStrategy, Component, input, signal } from '@angular/core';
|
||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule, NgOptimizedImage } from '@angular/common';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-carousel',
|
selector: 'app-product-carousel',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [CommonModule],
|
imports: [CommonModule, NgOptimizedImage],
|
||||||
templateUrl: './product-carousel.component.html',
|
templateUrl: './product-carousel.component.html',
|
||||||
styleUrl: './product-carousel.component.scss',
|
styleUrl: './product-carousel.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
})
|
})
|
||||||
export class ProductCarouselComponent {
|
export class ProductCarouselComponent {
|
||||||
readonly images = input<string[]>([]);
|
readonly images = input<string[]>([]);
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,8 @@
|
||||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||||
import {
|
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||||
BrowserTestingModule,
|
|
||||||
platformBrowserTesting
|
|
||||||
} from '@angular/platform-browser/testing';
|
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { BehaviorSubject, of, throwError } from 'rxjs';
|
import { BehaviorSubject, of, throwError } from 'rxjs';
|
||||||
import { convertToParamMap } from '@angular/router';
|
|
||||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import { ProductDetail } from '../../../../core/services/catalog/catalog.interface';
|
import { ProductDetail } from '../../../../core/services/catalog/catalog.interface';
|
||||||
|
|
@ -14,6 +10,10 @@ import { CatalogService } from '../../../../core/services/catalog/catalog.servic
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import { ProductDetailPageComponent } from './product-detail-page.component';
|
import { ProductDetailPageComponent } from './product-detail-page.component';
|
||||||
|
import {
|
||||||
|
PRODUCT_DETAIL_ERROR_MESSAGE,
|
||||||
|
ProductDetailResolvedData,
|
||||||
|
} from './product-detail-page.resolver';
|
||||||
|
|
||||||
describe('ProductDetailPageComponent', () => {
|
describe('ProductDetailPageComponent', () => {
|
||||||
const mockProduct: ProductDetail = {
|
const mockProduct: ProductDetail = {
|
||||||
|
|
@ -29,10 +29,10 @@ describe('ProductDetailPageComponent', () => {
|
||||||
images: ['https://example.com/image.png'],
|
images: ['https://example.com/image.png'],
|
||||||
attributes: [],
|
attributes: [],
|
||||||
variants_map: [],
|
variants_map: [],
|
||||||
variant: null
|
variant: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
let paramMapSubject: BehaviorSubject<any>;
|
let routeDataSubject: BehaviorSubject<{ productDetailData: ProductDetailResolvedData }>;
|
||||||
let catalogServiceStub: any;
|
let catalogServiceStub: any;
|
||||||
let routerStub: any;
|
let routerStub: any;
|
||||||
let cartServiceStub: any;
|
let cartServiceStub: any;
|
||||||
|
|
@ -40,10 +40,7 @@ describe('ProductDetailPageComponent', () => {
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
try {
|
try {
|
||||||
getTestBed().initTestEnvironment(
|
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
|
||||||
BrowserTestingModule,
|
|
||||||
platformBrowserTesting()
|
|
||||||
);
|
|
||||||
} catch {
|
} catch {
|
||||||
// Test environment may already be initialized by another setup entrypoint.
|
// Test environment may already be initialized by another setup entrypoint.
|
||||||
}
|
}
|
||||||
|
|
@ -51,20 +48,25 @@ describe('ProductDetailPageComponent', () => {
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
paramMapSubject = new BehaviorSubject(convertToParamMap({ id: '1' }));
|
routeDataSubject = new BehaviorSubject<{ productDetailData: ProductDetailResolvedData }>({
|
||||||
|
productDetailData: {
|
||||||
|
product: mockProduct,
|
||||||
|
error: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
catalogServiceStub = {
|
catalogServiceStub = {
|
||||||
getProducto: vi.fn().mockReturnValue(of(mockProduct))
|
getProducto: vi.fn(),
|
||||||
};
|
};
|
||||||
routerStub = {
|
routerStub = {
|
||||||
navigate: vi.fn()
|
navigate: vi.fn(),
|
||||||
};
|
};
|
||||||
cartServiceStub = {
|
cartServiceStub = {
|
||||||
addItem: vi.fn().mockReturnValue(of({ message: 'Producto agregado al carrito' }))
|
addItem: vi.fn().mockReturnValue(of({ message: 'Producto agregado al carrito' })),
|
||||||
};
|
};
|
||||||
toastServiceStub = {
|
toastServiceStub = {
|
||||||
success: vi.fn(),
|
success: vi.fn(),
|
||||||
danger: vi.fn(),
|
danger: vi.fn(),
|
||||||
info: vi.fn()
|
info: vi.fn(),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -75,47 +77,69 @@ describe('ProductDetailPageComponent', () => {
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
useValue: {
|
useValue: {
|
||||||
paramMap: paramMapSubject.asObservable()
|
data: routeDataSubject.asObservable(),
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
provide: CatalogService,
|
provide: CatalogService,
|
||||||
useValue: catalogServiceStub
|
useValue: catalogServiceStub,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
provide: Router,
|
provide: Router,
|
||||||
useValue: routerStub
|
useValue: routerStub,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
provide: CartService,
|
provide: CartService,
|
||||||
useValue: cartServiceStub
|
useValue: cartServiceStub,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
provide: ToastService,
|
provide: ToastService,
|
||||||
useValue: toastServiceStub
|
useValue: toastServiceStub,
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
}
|
}
|
||||||
|
|
||||||
it('loads the product on init and embeds the carousel', async () => {
|
function resolveProduct(product: ProductDetail): void {
|
||||||
|
routeDataSubject.next({
|
||||||
|
productDetailData: {
|
||||||
|
product,
|
||||||
|
error: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveProductError(error: string): void {
|
||||||
|
routeDataSubject.next({
|
||||||
|
productDetailData: {
|
||||||
|
product: null,
|
||||||
|
error,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
it('renders the resolved product and embeds the carousel', async () => {
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const element = fixture.nativeElement as HTMLElement;
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
|
||||||
expect(catalogServiceStub.getProducto).toHaveBeenCalledWith(1);
|
expect(catalogServiceStub.getProducto).not.toHaveBeenCalled();
|
||||||
|
|
||||||
expect(element.querySelector('app-product-carousel')).not.toBeNull();
|
expect(element.querySelector('app-product-carousel')).not.toBeNull();
|
||||||
expect(element.querySelector('.product-detail__title')?.textContent).toContain('Auriculares Bluetooth');
|
expect(element.querySelector('.product-detail__title')?.textContent).toContain(
|
||||||
expect(element.querySelector('.product-detail__price-current')?.textContent).toContain('$24.999');
|
'Auriculares Bluetooth',
|
||||||
|
);
|
||||||
|
expect(element.querySelector('.product-detail__price-current')?.textContent).toContain(
|
||||||
|
'$24.999',
|
||||||
|
);
|
||||||
expect(element.querySelector('.product-detail__price-previous')).toBeNull();
|
expect(element.querySelector('.product-detail__price-previous')).toBeNull();
|
||||||
expect(element.querySelector('.product-carousel__discount-badge')).toBeNull();
|
expect(element.querySelector('.product-carousel__discount-badge')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows error message if load fails', async () => {
|
it('shows error message if the resolver cannot load the product', async () => {
|
||||||
catalogServiceStub.getProducto.mockReturnValue(throwError(() => new Error('load failed')));
|
resolveProductError(PRODUCT_DETAIL_ERROR_MESSAGE);
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
@ -125,7 +149,6 @@ describe('ProductDetailPageComponent', () => {
|
||||||
expect(element.textContent).toContain('No pudimos cargar los detalles del producto.');
|
expect(element.textContent).toContain('No pudimos cargar los detalles del producto.');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
it('should use default variant images if present', async () => {
|
it('should use default variant images if present', async () => {
|
||||||
const detailProduct: ProductDetail = {
|
const detailProduct: ProductDetail = {
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
|
|
@ -134,26 +157,29 @@ describe('ProductDetailPageComponent', () => {
|
||||||
id: 123,
|
id: 123,
|
||||||
cantidad_maxima: 10,
|
cantidad_maxima: 10,
|
||||||
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
|
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
|
||||||
definitions: {}
|
definitions: {},
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
|
resolveProduct(detailProduct);
|
||||||
|
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const carousel = fixture.debugElement.query(By.css('app-product-carousel')).componentInstance;
|
const carousel = fixture.debugElement.query(By.css('app-product-carousel')).componentInstance;
|
||||||
expect(carousel.images()).toEqual(['https://example.com/variant1.png', 'https://example.com/variant2.png']);
|
expect(carousel.images()).toEqual([
|
||||||
|
'https://example.com/variant1.png',
|
||||||
|
'https://example.com/variant2.png',
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fallback to product images if default variant images are not present', async () => {
|
it('should fallback to product images if default variant images are not present', async () => {
|
||||||
const detailProduct: ProductDetail = {
|
const detailProduct: ProductDetail = {
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
images: ['https://example.com/product.png'],
|
images: ['https://example.com/product.png'],
|
||||||
variant: null
|
variant: null,
|
||||||
};
|
};
|
||||||
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
|
resolveProduct(detailProduct);
|
||||||
|
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
|
|
@ -167,9 +193,9 @@ describe('ProductDetailPageComponent', () => {
|
||||||
const detailProduct: ProductDetail = {
|
const detailProduct: ProductDetail = {
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
images: [],
|
images: [],
|
||||||
variant: null
|
variant: null,
|
||||||
};
|
};
|
||||||
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
|
resolveProduct(detailProduct);
|
||||||
|
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
|
|
@ -196,16 +222,16 @@ describe('ProductDetailPageComponent', () => {
|
||||||
value: 'beige',
|
value: 'beige',
|
||||||
label: 'Beige',
|
label: 'Beige',
|
||||||
sort_order: 1,
|
sort_order: 1,
|
||||||
metadata: { hex: '#D8D1C7' }
|
metadata: { hex: '#D8D1C7' },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 11,
|
id: 11,
|
||||||
value: 'brown',
|
value: 'brown',
|
||||||
label: 'Marrón',
|
label: 'Marrón',
|
||||||
sort_order: 2,
|
sort_order: 2,
|
||||||
metadata: { palette: { primary: '#7E6460' } }
|
metadata: { palette: { primary: '#7E6460' } },
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
|
|
@ -220,17 +246,17 @@ describe('ProductDetailPageComponent', () => {
|
||||||
value: 'mesh',
|
value: 'mesh',
|
||||||
label: 'Mesh',
|
label: 'Mesh',
|
||||||
sort_order: 1,
|
sort_order: 1,
|
||||||
metadata: null
|
metadata: null,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 21,
|
id: 21,
|
||||||
value: 'cuero',
|
value: 'cuero',
|
||||||
label: 'Cuero',
|
label: 'Cuero',
|
||||||
sort_order: 2,
|
sort_order: 2,
|
||||||
metadata: null
|
metadata: null,
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
variant: {
|
variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
|
|
@ -238,11 +264,11 @@ describe('ProductDetailPageComponent', () => {
|
||||||
images: ['https://example.com/variant1.png'],
|
images: ['https://example.com/variant1.png'],
|
||||||
definitions: {
|
definitions: {
|
||||||
color: 'beige',
|
color: 'beige',
|
||||||
material: 'Cuero'
|
material: 'Cuero',
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
|
resolveProduct(detailProduct);
|
||||||
|
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
|
|
@ -252,14 +278,16 @@ describe('ProductDetailPageComponent', () => {
|
||||||
const swatches = element.querySelectorAll('.attribute-selector__swatch');
|
const swatches = element.querySelectorAll('.attribute-selector__swatch');
|
||||||
const textOptions = element.querySelectorAll('.attribute-selector__text-option');
|
const textOptions = element.querySelectorAll('.attribute-selector__text-option');
|
||||||
const labels = Array.from(element.querySelectorAll('.attribute-selector__label')).map((label) =>
|
const labels = Array.from(element.querySelectorAll('.attribute-selector__label')).map((label) =>
|
||||||
label.textContent?.trim()
|
label.textContent?.trim(),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(labels).toEqual(['Color:', 'Material:']);
|
expect(labels).toEqual(['Color:', 'Material:']);
|
||||||
expect(swatches).toHaveLength(2);
|
expect(swatches).toHaveLength(2);
|
||||||
expect(textOptions).toHaveLength(2);
|
expect(textOptions).toHaveLength(2);
|
||||||
expect(swatches[0].classList.contains('attribute-selector__swatch--selected')).toBe(true);
|
expect(swatches[0].classList.contains('attribute-selector__swatch--selected')).toBe(true);
|
||||||
expect(textOptions[1].classList.contains('attribute-selector__text-option--selected')).toBe(true);
|
expect(textOptions[1].classList.contains('attribute-selector__text-option--selected')).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
expect((swatches[0] as HTMLElement).style.backgroundColor).not.toBe('');
|
expect((swatches[0] as HTMLElement).style.backgroundColor).not.toBe('');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -282,16 +310,16 @@ describe('ProductDetailPageComponent', () => {
|
||||||
fixture.componentInstance['selectedVariant'].set({
|
fixture.componentInstance['selectedVariant'].set({
|
||||||
variant_id: 1,
|
variant_id: 1,
|
||||||
cantidad_maxima: 10,
|
cantidad_maxima: 10,
|
||||||
attributes: {}
|
attributes: {},
|
||||||
});
|
});
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const element = fixture.nativeElement as HTMLElement;
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
const decreaseButton = element.querySelector(
|
const decreaseButton = element.querySelector(
|
||||||
'[aria-label="Disminuir cantidad"]'
|
'[aria-label="Disminuir cantidad"]',
|
||||||
) as HTMLButtonElement;
|
) as HTMLButtonElement;
|
||||||
const increaseButton = element.querySelector(
|
const increaseButton = element.querySelector(
|
||||||
'[aria-label="Aumentar cantidad"]'
|
'[aria-label="Aumentar cantidad"]',
|
||||||
) as HTMLButtonElement;
|
) as HTMLButtonElement;
|
||||||
|
|
||||||
decreaseButton.click();
|
decreaseButton.click();
|
||||||
|
|
@ -316,7 +344,7 @@ describe('ProductDetailPageComponent', () => {
|
||||||
|
|
||||||
const element = fixture.nativeElement as HTMLElement;
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
const toggleButton = element.querySelector(
|
const toggleButton = element.querySelector(
|
||||||
'.product-detail__description-toggle'
|
'.product-detail__description-toggle',
|
||||||
) as HTMLButtonElement;
|
) as HTMLButtonElement;
|
||||||
|
|
||||||
expect(toggleButton.textContent?.trim()).toBe('Mostrar más');
|
expect(toggleButton.textContent?.trim()).toBe('Mostrar más');
|
||||||
|
|
@ -327,7 +355,7 @@ describe('ProductDetailPageComponent', () => {
|
||||||
expect(
|
expect(
|
||||||
element
|
element
|
||||||
.querySelector('.product-detail__description-body')
|
.querySelector('.product-detail__description-body')
|
||||||
?.classList.contains('product-detail__description-body--expanded')
|
?.classList.contains('product-detail__description-body--expanded'),
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
expect(toggleButton.textContent?.trim()).toBe('Mostrar menos');
|
expect(toggleButton.textContent?.trim()).toBe('Mostrar menos');
|
||||||
});
|
});
|
||||||
|
|
@ -338,12 +366,12 @@ describe('ProductDetailPageComponent', () => {
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const buttons = Array.from(
|
const buttons = Array.from(
|
||||||
fixture.nativeElement.querySelectorAll('app-button button')
|
fixture.nativeElement.querySelectorAll('app-button button'),
|
||||||
) as HTMLButtonElement[];
|
) as HTMLButtonElement[];
|
||||||
|
|
||||||
expect(buttons.map((button) => button.textContent?.trim())).toEqual([
|
expect(buttons.map((button) => button.textContent?.trim())).toEqual([
|
||||||
'Agregar al carrito',
|
'Agregar al carrito',
|
||||||
'Comprar'
|
'Comprar',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
buttons[0].click();
|
buttons[0].click();
|
||||||
|
|
@ -359,17 +387,17 @@ describe('ProductDetailPageComponent', () => {
|
||||||
id: 123,
|
id: 123,
|
||||||
cantidad_maxima: 5,
|
cantidad_maxima: 5,
|
||||||
images: [],
|
images: [],
|
||||||
definitions: {}
|
definitions: {},
|
||||||
},
|
},
|
||||||
variants_map: [
|
variants_map: [
|
||||||
{
|
{
|
||||||
variant_id: 123,
|
variant_id: 123,
|
||||||
cantidad_maxima: 5,
|
cantidad_maxima: 5,
|
||||||
attributes: {}
|
attributes: {},
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
};
|
};
|
||||||
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
|
resolveProduct(detailProduct);
|
||||||
|
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
|
|
@ -382,7 +410,7 @@ describe('ProductDetailPageComponent', () => {
|
||||||
|
|
||||||
const element = fixture.nativeElement as HTMLElement;
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
const addToCartButton = Array.from(element.querySelectorAll('app-button button')).find(
|
const addToCartButton = Array.from(element.querySelectorAll('app-button button')).find(
|
||||||
(btn) => btn.textContent?.trim() === 'Agregar al carrito'
|
(btn) => btn.textContent?.trim() === 'Agregar al carrito',
|
||||||
) as HTMLButtonElement;
|
) as HTMLButtonElement;
|
||||||
|
|
||||||
expect(addToCartButton).toBeDefined();
|
expect(addToCartButton).toBeDefined();
|
||||||
|
|
@ -400,17 +428,17 @@ describe('ProductDetailPageComponent', () => {
|
||||||
id: 123,
|
id: 123,
|
||||||
cantidad_maxima: 5,
|
cantidad_maxima: 5,
|
||||||
images: [],
|
images: [],
|
||||||
definitions: {}
|
definitions: {},
|
||||||
},
|
},
|
||||||
variants_map: [
|
variants_map: [
|
||||||
{
|
{
|
||||||
variant_id: 123,
|
variant_id: 123,
|
||||||
cantidad_maxima: 5,
|
cantidad_maxima: 5,
|
||||||
attributes: {}
|
attributes: {},
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
};
|
};
|
||||||
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
|
resolveProduct(detailProduct);
|
||||||
cartServiceStub.addItem.mockReturnValue(throwError(() => new Error('Failed to add')));
|
cartServiceStub.addItem.mockReturnValue(throwError(() => new Error('Failed to add')));
|
||||||
|
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
|
|
@ -422,13 +450,15 @@ describe('ProductDetailPageComponent', () => {
|
||||||
|
|
||||||
const element = fixture.nativeElement as HTMLElement;
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
const addToCartButton = Array.from(element.querySelectorAll('app-button button')).find(
|
const addToCartButton = Array.from(element.querySelectorAll('app-button button')).find(
|
||||||
(btn) => btn.textContent?.trim() === 'Agregar al carrito'
|
(btn) => btn.textContent?.trim() === 'Agregar al carrito',
|
||||||
) as HTMLButtonElement;
|
) as HTMLButtonElement;
|
||||||
|
|
||||||
addToCartButton.click();
|
addToCartButton.click();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(cartServiceStub.addItem).toHaveBeenCalled();
|
expect(cartServiceStub.addItem).toHaveBeenCalled();
|
||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith('No se pudo agregar el producto al carrito.');
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
|
'No se pudo agregar el producto al carrito.',
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import {
|
||||||
inject,
|
inject,
|
||||||
signal,
|
signal,
|
||||||
viewChild,
|
viewChild,
|
||||||
PLATFORM_ID
|
PLATFORM_ID,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { CommonModule, isPlatformBrowser } from '@angular/common';
|
import { CommonModule, isPlatformBrowser } from '@angular/common';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
|
@ -20,16 +20,14 @@ import { CatalogService } from '../../../../core/services/catalog/catalog.servic
|
||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import {
|
import {
|
||||||
ProductAttribute,
|
|
||||||
ProductAttributeOption,
|
|
||||||
ProductDetail,
|
ProductDetail,
|
||||||
ProductVariant,
|
ProductVariantMap,
|
||||||
ProductVariantMap
|
|
||||||
} from '../../../../core/services/catalog/catalog.interface';
|
} from '../../../../core/services/catalog/catalog.interface';
|
||||||
import { ProductCarouselComponent } from '../../components/product-carousel/product-carousel.component';
|
import { ProductCarouselComponent } from '../../components/product-carousel/product-carousel.component';
|
||||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||||
import { ProductAttributeSelectorComponent } from '../../components/product-attribute-selector/product-attribute-selector.component';
|
import { ProductAttributeSelectorComponent } from '../../components/product-attribute-selector/product-attribute-selector.component';
|
||||||
import { QuantitySelectorComponent } from '../../../../shared/components/quantity-selector/quantity-selector.component';
|
import { QuantitySelectorComponent } from '../../../../shared/components/quantity-selector/quantity-selector.component';
|
||||||
|
import { ProductDetailResolvedData } from './product-detail-page.resolver';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-detail-page',
|
selector: 'app-product-detail-page',
|
||||||
|
|
@ -40,11 +38,11 @@ import { QuantitySelectorComponent } from '../../../../shared/components/quantit
|
||||||
ProductCarouselComponent,
|
ProductCarouselComponent,
|
||||||
ButtonComponent,
|
ButtonComponent,
|
||||||
ProductAttributeSelectorComponent,
|
ProductAttributeSelectorComponent,
|
||||||
QuantitySelectorComponent
|
QuantitySelectorComponent,
|
||||||
],
|
],
|
||||||
templateUrl: './product-detail-page.component.html',
|
templateUrl: './product-detail-page.component.html',
|
||||||
styleUrl: './product-detail-page.component.scss',
|
styleUrl: './product-detail-page.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
})
|
})
|
||||||
export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||||
private readonly route = inject(ActivatedRoute);
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
|
@ -86,14 +84,14 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||||
protected readonly descriptionMaxHeight = signal(0);
|
protected readonly descriptionMaxHeight = signal(0);
|
||||||
protected readonly descriptionHasOverflow = signal(false);
|
protected readonly descriptionHasOverflow = signal(false);
|
||||||
protected readonly renderableAttributes = computed(() =>
|
protected readonly renderableAttributes = computed(() =>
|
||||||
(this.product()?.attributes ?? []).filter((attribute) => attribute.options.length > 0)
|
(this.product()?.attributes ?? []).filter((attribute) => attribute.options.length > 0),
|
||||||
);
|
);
|
||||||
protected readonly hasRenderableAttributes = computed(
|
protected readonly hasRenderableAttributes = computed(
|
||||||
() => this.renderableAttributes().length > 0
|
() => this.renderableAttributes().length > 0,
|
||||||
);
|
);
|
||||||
protected readonly oldPrice = computed<string | null>(() => null);
|
protected readonly oldPrice = computed<string | null>(() => null);
|
||||||
protected readonly showDescriptionToggle = computed(
|
protected readonly showDescriptionToggle = computed(
|
||||||
() => this.descriptionExpanded() || this.descriptionHasOverflow()
|
() => this.descriptionExpanded() || this.descriptionHasOverflow(),
|
||||||
);
|
);
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
|
|
@ -113,14 +111,12 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.routeSub = this.route.paramMap.subscribe((params) => {
|
this.routeSub = this.route.data.subscribe((data) => {
|
||||||
const id = this.parseIntegerParam(params.get('id'));
|
const resolvedData = data['productDetailData'] as ProductDetailResolvedData | undefined;
|
||||||
if (id === null) {
|
|
||||||
this.error.set('ID de producto inválido');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.loadProduct(id);
|
if (resolvedData) {
|
||||||
|
this.applyResolvedData(resolvedData);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -131,38 +127,13 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||||
this.clearMeasurementTimer();
|
this.clearMeasurementTimer();
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadProduct(id: number): void {
|
|
||||||
this.loading.set(true);
|
|
||||||
this.error.set(null);
|
|
||||||
this.product.set(null);
|
|
||||||
|
|
||||||
this.productSub?.unsubscribe();
|
|
||||||
this.productSub = this.catalogService.getProducto(id).subscribe({
|
|
||||||
next: (prod) => {
|
|
||||||
this.product.set(prod);
|
|
||||||
const matchingVariant = prod.variants_map.find((v) => v.variant_id === prod.variant?.id) || null;
|
|
||||||
this.selectedVariant.set(matchingVariant);
|
|
||||||
this.quantity.set(1);
|
|
||||||
this.descriptionExpanded.set(false);
|
|
||||||
this.descriptionHasOverflow.set(false);
|
|
||||||
this.loading.set(false);
|
|
||||||
},
|
|
||||||
error: () => {
|
|
||||||
this.error.set('No pudimos cargar los detalles del producto.');
|
|
||||||
this.loading.set(false);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private loadProductVariant(productId: number, variantId: number): void {
|
private loadProductVariant(productId: number, variantId: number): void {
|
||||||
this.variantLoading.set(true);
|
this.variantLoading.set(true);
|
||||||
|
|
||||||
this.productSub?.unsubscribe();
|
this.productSub?.unsubscribe();
|
||||||
this.productSub = this.catalogService.getProducto(productId, variantId).subscribe({
|
this.productSub = this.catalogService.getProducto(productId, variantId).subscribe({
|
||||||
next: (prod) => {
|
next: (prod) => {
|
||||||
this.product.set(prod);
|
this.applyProduct(prod, false);
|
||||||
const matchingVariant = prod.variants_map.find((v) => v.variant_id === prod.variant?.id) || null;
|
|
||||||
this.selectedVariant.set(matchingVariant);
|
|
||||||
this.variantLoading.set(false);
|
this.variantLoading.set(false);
|
||||||
},
|
},
|
||||||
error: (err: HttpErrorResponse) => {
|
error: (err: HttpErrorResponse) => {
|
||||||
|
|
@ -180,15 +151,44 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
...currentProduct,
|
...currentProduct,
|
||||||
variants_map: updatedVariantsMap
|
variants_map: updatedVariantsMap,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
this.attributeSelector()?.reset();
|
this.attributeSelector()?.reset();
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private applyResolvedData(resolvedData: ProductDetailResolvedData): void {
|
||||||
|
this.productSub?.unsubscribe();
|
||||||
|
this.loading.set(false);
|
||||||
|
this.variantLoading.set(false);
|
||||||
|
|
||||||
|
if (resolvedData.error) {
|
||||||
|
this.product.set(null);
|
||||||
|
this.error.set(resolvedData.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resolvedData.product) {
|
||||||
|
this.applyProduct(resolvedData.product, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private applyProduct(prod: ProductDetail, resetQuantity: boolean): void {
|
||||||
|
this.product.set(prod);
|
||||||
|
const matchingVariant =
|
||||||
|
prod.variants_map.find((v) => v.variant_id === prod.variant?.id) || null;
|
||||||
|
this.selectedVariant.set(matchingVariant);
|
||||||
|
if (resetQuantity) {
|
||||||
|
this.quantity.set(1);
|
||||||
|
}
|
||||||
|
this.descriptionExpanded.set(false);
|
||||||
|
this.descriptionHasOverflow.set(false);
|
||||||
|
this.error.set(null);
|
||||||
|
}
|
||||||
|
|
||||||
protected goBack(): void {
|
protected goBack(): void {
|
||||||
this.router.navigate(['/']);
|
this.router.navigate(['/']);
|
||||||
}
|
}
|
||||||
|
|
@ -219,8 +219,6 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
protected addToCart(): void {
|
protected addToCart(): void {
|
||||||
const variant = this.selectedVariant();
|
const variant = this.selectedVariant();
|
||||||
if (!variant) {
|
if (!variant) {
|
||||||
|
|
@ -239,7 +237,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||||
const errorMessage = err.error?.message || 'No se pudo agregar el producto al carrito.';
|
const errorMessage = err.error?.message || 'No se pudo agregar el producto al carrito.';
|
||||||
this.toastService.danger(errorMessage);
|
this.toastService.danger(errorMessage);
|
||||||
this.addingToCart.set(false);
|
this.addingToCart.set(false);
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -247,15 +245,6 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||||
this.descriptionExpanded.update((current) => !current);
|
this.descriptionExpanded.update((current) => !current);
|
||||||
}
|
}
|
||||||
|
|
||||||
private parseIntegerParam(value: string | null): number | null {
|
|
||||||
if (!value) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const parsed = Number(value);
|
|
||||||
return Number.isInteger(parsed) ? parsed : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private bindCarouselResizeObserver(): void {
|
private bindCarouselResizeObserver(): void {
|
||||||
const previewElement = this.getCarouselPreviewElement();
|
const previewElement = this.getCarouselPreviewElement();
|
||||||
|
|
||||||
|
|
@ -315,7 +304,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||||
}
|
}
|
||||||
|
|
||||||
this.descriptionHasOverflow.set(
|
this.descriptionHasOverflow.set(
|
||||||
descriptionElement.scrollHeight - descriptionElement.clientHeight > 1
|
descriptionElement.scrollHeight - descriptionElement.clientHeight > 1,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,91 @@
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { convertToParamMap } from '@angular/router';
|
||||||
|
import { firstValueFrom, Observable, of, throwError } from 'rxjs';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { ProductDetail } from '../../../../core/services/catalog/catalog.interface';
|
||||||
|
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||||
|
import {
|
||||||
|
PRODUCT_DETAIL_ERROR_MESSAGE,
|
||||||
|
PRODUCT_DETAIL_INVALID_ID_MESSAGE,
|
||||||
|
ProductDetailResolvedData,
|
||||||
|
productDetailResolver,
|
||||||
|
} from './product-detail-page.resolver';
|
||||||
|
|
||||||
|
describe('productDetailResolver', () => {
|
||||||
|
const product: ProductDetail = {
|
||||||
|
id: 1,
|
||||||
|
category_id: 10,
|
||||||
|
brand_id: null,
|
||||||
|
slug: 'auriculares-bluetooth',
|
||||||
|
nombre: 'Auriculares Bluetooth',
|
||||||
|
descripcion: 'Auriculares bluetooth de prueba',
|
||||||
|
precio: '24999',
|
||||||
|
category: 'Tecnologia',
|
||||||
|
brand: null,
|
||||||
|
images: [],
|
||||||
|
attributes: [],
|
||||||
|
variants_map: [],
|
||||||
|
variant: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
let catalogServiceStub: { getProducto: ReturnType<typeof vi.fn> };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
catalogServiceStub = {
|
||||||
|
getProducto: vi.fn().mockReturnValue(of(product)),
|
||||||
|
};
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: CatalogService,
|
||||||
|
useValue: catalogServiceStub,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves the product detail for the route id', async () => {
|
||||||
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
|
productDetailResolver(createRouteSnapshot('1'), {} as never),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(firstValueFrom(result as Observable<ProductDetailResolvedData>)).resolves.toEqual({
|
||||||
|
product,
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
expect(catalogServiceStub.getProducto).toHaveBeenCalledWith(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns an error state for invalid ids', async () => {
|
||||||
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
|
productDetailResolver(createRouteSnapshot('abc'), {} as never),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(firstValueFrom(result as Observable<ProductDetailResolvedData>)).resolves.toEqual({
|
||||||
|
product: null,
|
||||||
|
error: PRODUCT_DETAIL_INVALID_ID_MESSAGE,
|
||||||
|
});
|
||||||
|
expect(catalogServiceStub.getProducto).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns an error state when the request fails', async () => {
|
||||||
|
catalogServiceStub.getProducto.mockReturnValue(throwError(() => new Error('boom')));
|
||||||
|
|
||||||
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
|
productDetailResolver(createRouteSnapshot('1'), {} as never),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(firstValueFrom(result as Observable<ProductDetailResolvedData>)).resolves.toEqual({
|
||||||
|
product: null,
|
||||||
|
error: PRODUCT_DETAIL_ERROR_MESSAGE,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function createRouteSnapshot(id: string) {
|
||||||
|
return {
|
||||||
|
paramMap: convertToParamMap({ id }),
|
||||||
|
} as never;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
import { inject } from '@angular/core';
|
||||||
|
import { ActivatedRouteSnapshot, ResolveFn } from '@angular/router';
|
||||||
|
import { catchError, map, of } from 'rxjs';
|
||||||
|
|
||||||
|
import { ProductDetail } from '../../../../core/services/catalog/catalog.interface';
|
||||||
|
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||||
|
|
||||||
|
export const PRODUCT_DETAIL_ERROR_MESSAGE = 'No pudimos cargar los detalles del producto.';
|
||||||
|
export const PRODUCT_DETAIL_INVALID_ID_MESSAGE = 'ID de producto invalido';
|
||||||
|
|
||||||
|
export interface ProductDetailResolvedData {
|
||||||
|
product: ProductDetail | null;
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const productDetailResolver: ResolveFn<ProductDetailResolvedData> = (
|
||||||
|
route: ActivatedRouteSnapshot,
|
||||||
|
) => {
|
||||||
|
const productId = parseIntegerParam(route.paramMap.get('id'));
|
||||||
|
|
||||||
|
if (productId === null) {
|
||||||
|
return of({
|
||||||
|
product: null,
|
||||||
|
error: PRODUCT_DETAIL_INVALID_ID_MESSAGE,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return inject(CatalogService)
|
||||||
|
.getProducto(productId)
|
||||||
|
.pipe(
|
||||||
|
map(
|
||||||
|
(product): ProductDetailResolvedData => ({
|
||||||
|
product,
|
||||||
|
error: null,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
catchError(() =>
|
||||||
|
of({
|
||||||
|
product: null,
|
||||||
|
error: PRODUCT_DETAIL_ERROR_MESSAGE,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
function parseIntegerParam(value: string | null): number | null {
|
||||||
|
if (!value) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = Number(value);
|
||||||
|
return Number.isInteger(parsed) ? parsed : null;
|
||||||
|
}
|
||||||
|
|
@ -4,6 +4,7 @@ import { SimpleLayoutComponent } from '../../core/layout/simple-layout/simple-la
|
||||||
import { StoreLayoutComponent } from '../../core/layout/store-layout/store-layout.component';
|
import { StoreLayoutComponent } from '../../core/layout/store-layout/store-layout.component';
|
||||||
import { authGuard, guestOnlyGuard } from '../../core/services/auth/auth.guards';
|
import { authGuard, guestOnlyGuard } from '../../core/services/auth/auth.guards';
|
||||||
import { LoginPageComponent } from './pages/login-page/login-page.component';
|
import { LoginPageComponent } from './pages/login-page/login-page.component';
|
||||||
|
import { productDetailResolver } from './pages/product-detail-page/product-detail-page.resolver';
|
||||||
import { RegisterPageComponent } from './pages/register-page/register-page.component';
|
import { RegisterPageComponent } from './pages/register-page/register-page.component';
|
||||||
import { StoreHomePageComponent } from './pages/store-home-page/store-home-page.component';
|
import { StoreHomePageComponent } from './pages/store-home-page/store-home-page.component';
|
||||||
import { storeHomeProductsResolver } from './pages/store-home-page/store-home-page.resolver';
|
import { storeHomeProductsResolver } from './pages/store-home-page/store-home-page.resolver';
|
||||||
|
|
@ -17,8 +18,8 @@ export const routes: Routes = [
|
||||||
path: '',
|
path: '',
|
||||||
component: StoreHomePageComponent,
|
component: StoreHomePageComponent,
|
||||||
resolve: {
|
resolve: {
|
||||||
productsData: storeHomeProductsResolver
|
productsData: storeHomeProductsResolver,
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'login',
|
path: 'login',
|
||||||
|
|
@ -27,9 +28,9 @@ export const routes: Routes = [
|
||||||
children: [
|
children: [
|
||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
component: LoginPageComponent
|
component: LoginPageComponent,
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'register',
|
path: 'register',
|
||||||
|
|
@ -38,24 +39,27 @@ export const routes: Routes = [
|
||||||
children: [
|
children: [
|
||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
component: RegisterPageComponent
|
component: RegisterPageComponent,
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'producto/:id',
|
path: 'producto/:id',
|
||||||
|
resolve: {
|
||||||
|
productDetailData: productDetailResolver,
|
||||||
|
},
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
import('./pages/product-detail-page/product-detail-page.component').then(
|
import('./pages/product-detail-page/product-detail-page.component').then(
|
||||||
(m) => m.ProductDetailPageComponent
|
(m) => m.ProductDetailPageComponent,
|
||||||
)
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'checkout',
|
path: 'checkout',
|
||||||
canActivate: [authGuard],
|
canActivate: [authGuard],
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
import('./pages/checkout-page/checkout-page.component').then(
|
import('./pages/checkout-page/checkout-page.component').then(
|
||||||
(m) => m.CheckoutPageComponent
|
(m) => m.CheckoutPageComponent,
|
||||||
)
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'checkout/status',
|
path: 'checkout/status',
|
||||||
|
|
@ -65,47 +69,45 @@ export const routes: Routes = [
|
||||||
path: ':id',
|
path: ':id',
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
import('./pages/purchase-status-page/purchase-status-page.component').then(
|
import('./pages/purchase-status-page/purchase-status-page.component').then(
|
||||||
(m) => m.PurchaseStatusPageComponent
|
(m) => m.PurchaseStatusPageComponent,
|
||||||
)
|
),
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'mi-cuenta',
|
path: 'mi-cuenta',
|
||||||
canActivate: [authGuard],
|
canActivate: [authGuard],
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
import('./pages/account-page/account-layout/account-layout').then(
|
import('./pages/account-page/account-layout/account-layout').then((m) => m.AccountLayout),
|
||||||
(m) => m.AccountLayout
|
|
||||||
),
|
|
||||||
children: [
|
children: [
|
||||||
{
|
{
|
||||||
path: 'datos-personales',
|
path: 'datos-personales',
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
import('./pages/account-page/pages/profile-page/profile-page').then(
|
import('./pages/account-page/pages/profile-page/profile-page').then(
|
||||||
(m) => m.ProfilePage
|
(m) => m.ProfilePage,
|
||||||
)
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'compras',
|
path: 'compras',
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
import('./pages/account-page/pages/purchases-page/purchases-page').then(
|
import('./pages/account-page/pages/purchases-page/purchases-page').then(
|
||||||
(m) => m.PurchasesPage
|
(m) => m.PurchasesPage,
|
||||||
)
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'compras/:id',
|
path: 'compras/:id',
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
import('./pages/account-page/pages/purchase-detail-page/purchase-detail-page').then(
|
import('./pages/account-page/pages/purchase-detail-page/purchase-detail-page').then(
|
||||||
(m) => m.PurchaseDetailPage
|
(m) => m.PurchaseDetailPage,
|
||||||
)
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
redirectTo: 'datos-personales',
|
redirectTo: 'datos-personales',
|
||||||
pathMatch: 'full'
|
pathMatch: 'full',
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
}
|
},
|
||||||
];
|
];
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue