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 filter product list (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();
});
});
});
我正在尝试编写测试用例以过滤产品列表并编写了产品间谍,但它给出了错误:
TypeError: Cannot read property 'returnValue' of undefined
针对以下行:
productSpy.calls.mostRecent().returnValue.then
我试图在线查找解决方案,但找不到合适的解决方案。
以下是我要测试的服务: 1. filterProductList-将输入一个字符串,并过滤产品名称列表并获得产品列表-一个匹配给定字符串参数的
@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
}];
答案 0 :(得分:0)
一直被监视的方法从未被调用,经过几次尝试和错误,我才得到它
fit('should test filter product list (done)', (done) => {
component.searchText = 'fresh';
let productSpy = spyOn(productService, 'filterProductList').withArgs('fresh').and.callThrough();
**component.filterProductList({});**
productSpy.calls.mostRecent().returnValue.then(() => {
fixture.detectChanges();
const value = debugElement.query(By.css('#product_0')).nativeElement.innerText;
expect(value).toContain(component.searchText);
done();
});
});