import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ProductListComponent } from './product-list.component';
import { FormsModule } from '@angular/forms';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { ProductService } from './product.service';
describe('ProductListComponent', () => {
let component: ProductListComponent;
let fixture: ComponentFixture<ProductListComponent>;
let debugElement: DebugElement;
let productService: ProductService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ProductListComponent ],
imports: [FormsModule],
providers: [ProductService]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProductListComponent);
productService = TestBed.get(ProductService);
component = fixture.componentInstance;
fixture.detectChanges();
debugElement = fixture.debugElement;
});
fit('should test the product list filtering functionality (done)', (done)=> {
//component.searchText='fresh';
let productSpy = spyOn(productService, 'filterProductList').withArgs('fresh').and.callThrough();
productSpy.calls.mostRecent().returnValue.then(()=>{
fixture.detectChanges();
const value = debugElement.query(By.css('#product_0')).nativeElement.innerText;
expect(value).toContain(component.searchText);
done();
});
});
});
I am currently working on a testing scenario for filtering the product list based on a search term. Although I have set up a spy for the ProductService, an error is encountered:
TypeError: Cannot read property 'returnValue' of undefined
This issue arises when trying to access the following line of code:
productSpy.calls.mostRecent().returnValue.then
Even after conducting online research, a suitable solution could not be found.
The service that this test case is meant to validate includes the following method: 1. filterProductList - This function receives a string parameter and filters the list of products to return the matching product.
@Injectable({
providedIn: 'root'
})
export class ProductService {
productList = PRODUCT_LIST;
constructor() { }
public getProductList(){
return of(this.productList);
}
public filterProductList(searchString: string): Promise<any>{
let dataObs: Observable<any>;
//dataObs = of(this.productList.filter( product => product.title.toLowerCase().indexOf(searchString) > -1));
//setTimeout(()=> { dataObs = of(this.productList.filter( product => product.title.toLowerCase().indexOf(searchString) > -1))},1000);
return of(this.productList.filter( product => product.title.toLowerCase().indexOf(searchString) > -1)).toPromise();
}
}
export const PRODUCT_LIST = [{
"title": "Brown eggs",
"type": "dairy",
"description": "Raw organic brown eggs in a basket",
"filename": "0.jpg",
"height": 600,
"width": 400,
"price": 28.1,
"rating": 4
}];