Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Yauheni Sakalou Angular test #58

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"@angular/platform-browser": "^14.0.0",
"@angular/platform-browser-dynamic": "^14.0.0",
"@angular/router": "^14.0.0",
"@ngneat/until-destroy": "^9.2.2",
"ag-grid-angular": "^28.0.0",
"ag-grid-community": "^28.0.2",
"rxjs": "~7.5.0",
Expand Down
11 changes: 10 additions & 1 deletion src/app/products/product-http.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,13 @@ export class ProductHttpService {
get(id: string) {
return this.http.get<Product>(`/api/products/${id}`);
}
}

search(query: string) {
return this.http.get<{
products: Product[];
total: number;
skip: number;
limit: number;
}>('/api/products/search', { params: { q: query }});
}
};
16 changes: 16 additions & 0 deletions src/app/products/product-list/product-list.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<div class="grid-header">
<button mat-raised-button color="primary" (click)="addProduct()">Add Product</button>

<mat-form-field>
<input matInput placeholder="Search..." [formControl]="searchFormControl"/>
</mat-form-field>
</div>

<ag-grid-angular
class="ag-theme-alpine"
[rowData]="products$ | async"
[gridOptions]="gridOptions"
[columnDefs]="columnDefs"
(rowDoubleClicked)="openProduct($event)"
></ag-grid-angular>
<mat-spinner *ngIf="loading$ | async" [diameter]="36" [mode]="'indeterminate'"></mat-spinner>
25 changes: 25 additions & 0 deletions src/app/products/product-list/product-list.component.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
:host {
display: block;
height: 100%;
width: 100%;
position: relative;
}

ag-grid-angular {
display: block;
width: 100%;
height: 100%;
}

mat-spinner {
position: absolute;
top: 0.5rem;
right: 0.5rem;
}

.grid-header {
display: flex;
flex-direction: row;
align-items: center;
gap: 0.5rem;
}
112 changes: 112 additions & 0 deletions src/app/products/product-list/product-list.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { MatBottomSheet, MatBottomSheetModule } from '@angular/material/bottom-sheet';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { AgGridModule } from 'ag-grid-angular';
import { of } from 'rxjs';
import { ProductDetailModule } from '../product-detail/product-detail.module';
import { Product } from '../product-http.service';
import { ProductService } from '../product.service';
import { ProductListComponent } from './product-list.component';

describe('ProductListComponent', () => {
let component: ProductListComponent;
let fixture: ComponentFixture<ProductListComponent>;
let productServiceMock: any;
let productsMock: Product[] = [
{
"id": 1,
"title": "iPhone 9",
"description": "An apple mobile which is nothing like apple",
"price": 549,
"discountPercentage": 12.96,
"rating": 4.69,
"stock": 94,
"brand": "Apple",
"category": "smartphones",
"thumbnail": "https://dummyjson.com/image/i/products/1/thumbnail.jpg",
"images": [
"https://dummyjson.com/image/i/products/1/1.jpg",
"https://dummyjson.com/image/i/products/1/2.jpg",
"https://dummyjson.com/image/i/products/1/3.jpg",
"https://dummyjson.com/image/i/products/1/4.jpg",
"https://dummyjson.com/image/i/products/1/thumbnail.jpg"
]
}
];
let bottomSheet: MatBottomSheet;

beforeEach((() => {
productServiceMock = {
getAll: jest.fn(),
searchByString: jest.fn(),
addProduct: jest.fn()
};

productServiceMock.getAll.mockReturnValue(of([...productsMock]));

TestBed.configureTestingModule({
imports: [
CommonModule,
AgGridModule,
MatProgressSpinnerModule,
MatBottomSheetModule,
MatInputModule,
MatFormFieldModule,
MatButtonModule,
ReactiveFormsModule,
ProductDetailModule,
NoopAnimationsModule,
],
declarations: [ProductListComponent],
schemas: [NO_ERRORS_SCHEMA],
providers: [{
provide: ProductService,
useValue: productServiceMock,
}]
}).compileComponents();

fixture = TestBed.createComponent(ProductListComponent);
bottomSheet = TestBed.inject(MatBottomSheet);
component = fixture.componentInstance;
fixture.detectChanges();
}));

it('should be created', () => {
expect(component).toBeTruthy();
});

describe('on init', () => {
it('getAll() should be called', () => {
expect(productServiceMock.getAll).toBeCalledTimes(1);
});

it('should be created', () => {
// Arrange
const searchFormControlSpy = jest.spyOn(component.searchFormControl['valueChanges'], 'subscribe');

// Act
component.ngOnInit();

// Assert
expect(searchFormControlSpy).toBeCalledTimes(1);
});
});

it('should call bottomSheetOpen when addProduct is called', async () => {
// Arrange
const bottomSheetOpenSpy = jest.spyOn(bottomSheet, 'open');

// Act
component.addProduct();

// Assert
expect(bottomSheetOpenSpy).toBeCalledTimes(1);
});
});
78 changes: 46 additions & 32 deletions src/app/products/product-list/product-list.component.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,25 @@
import { Component, OnInit } from '@angular/core';
import { MatBottomSheet } from '@angular/material/bottom-sheet';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { ColDef, GridOptions, RowDoubleClickedEvent } from 'ag-grid-community';
import { filter, switchMap } from 'rxjs';
import { combineLatest, debounceTime, filter, interval, map, Observable, startWith, switchMap } from 'rxjs';
import { ProductDetailComponent } from '../product-detail/product-detail.component';
import { Product } from '../product-http.service';
import { ProductService } from '../product.service';
import { FormControl } from '@angular/forms';

@UntilDestroy()
@Component({
selector: 'y42-product-list',
template: `<ag-grid-angular
class="ag-theme-alpine"
[rowData]="products$ | async"
[gridOptions]="gridOptions"
[columnDefs]="columnDefs"
(rowDoubleClicked)="openProduct($event)"
></ag-grid-angular>
<mat-spinner *ngIf="loading$ | async" [diameter]="36" [mode]="'indeterminate'"></mat-spinner> `,
styles: [
`
:host {
display: block;
height: 100%;
width: 100%;
position: relative;
}

ag-grid-angular {
display: block;
width: 100%;
height: 100%;
}

mat-spinner {
position: absolute;
top: 0.5rem;
right: 0.5rem;
}
`,
],
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.scss'],
})
export class ProductListComponent implements OnInit {
constructor(private productService: ProductService, private bottomSheet: MatBottomSheet) {}

readonly products$ = this.productService.products$;
readonly loading$ = this.productService.loading$;
readonly searchFormControl = new FormControl();

readonly gridOptions: GridOptions<Product> = {
suppressCellFocus: true,
Expand Down Expand Up @@ -108,7 +84,8 @@ export class ProductListComponent implements OnInit {
];

ngOnInit(): void {
this.productService.getAll().subscribe();
this.subscrGetAllProducts();
this.subscrSearchFormControl();
}

openProduct(params: RowDoubleClickedEvent<Product>): void {
Expand All @@ -129,7 +106,44 @@ export class ProductListComponent implements OnInit {
.pipe(
filter(Boolean),
switchMap((newProduct) => this.productService.updateProduct(id, newProduct)),
untilDestroyed(this),
)
.subscribe();
}

addProduct(): void {
const newId = Math.floor(Math.random() * 100);
const product: Product = {
id: newId, title: '', brand: '', description: '', stock: 0, price: 0, rating: 0,
discountPercentage: 0,
category: '',
thumbnail: '',
images: []
};

this.bottomSheet
.open<ProductDetailComponent, Product, Product>(ProductDetailComponent, { data: product })
.afterDismissed()
.pipe(
filter(Boolean),
switchMap((newProduct) => this.productService.createProduct(newProduct)),
untilDestroyed(this),
)
.subscribe();
}

private subscrGetAllProducts(): void {
this.productService
.getAll()
.pipe(untilDestroyed(this))
.subscribe();
}

private subscrSearchFormControl(): void {
this.searchFormControl.valueChanges.pipe(
debounceTime(400),
switchMap((query: string) => this.productService.searchByString(query)),
untilDestroyed(this),
).subscribe();
}
}
8 changes: 8 additions & 0 deletions src/app/products/product-list/product-list.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { RouterModule } from '@angular/router';
import { AgGridModule } from 'ag-grid-angular';
Expand All @@ -15,6 +19,10 @@ import { ProductListComponent } from './product-list.component';
AgGridModule,
MatProgressSpinnerModule,
MatBottomSheetModule,
MatButtonModule,
MatInputModule,
MatFormFieldModule,
ReactiveFormsModule,
ProductDetailModule,
RouterModule.forChild([
{
Expand Down
25 changes: 25 additions & 0 deletions src/app/products/product.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ export class ProductService {
);
}

searchByString(query: string) {
this.loading$$.next(true);

return this.productHttp
.search(query)
.pipe(
tap((response) => this.products$$.next(response.products)),
finalize(() => this.loading$$.next(false)),
);
}

updateProduct(id: number, newProduct: Partial<Product>) {
this.loading$$.next(true);

Expand All @@ -36,6 +47,20 @@ export class ProductService {
finalize(() => this.loading$$.next(false)),
);
}

createProduct(newProduct: Partial<Product>) {
this.loading$$.next(true);

const currentProductList = this.products$$.getValue();

return timer(750)
.pipe(
tap(() => {
this.products$$.next([...currentProductList, newProduct as Product]);
}),
finalize(() => this.loading$$.next(false)),
);
}

updateStock(id: number, newStock: number) {
this.loading$$.next(true);
Expand Down