我有 Angular 4 应用程序,我正在使用 jasmin + Karma 编写测试用例
我的第一个测试用例在创建组件和服务实例时正常工作,
但是第二个测试用例失败了,因为当我记录它的值未定义时,它无法获取“getorders”方法的模拟数据。
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ OrderListComponent ],
providers: [
OrderFormFetchService,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
RouterModule.forRoot([]),
NglModule.forRoot({svgPath: 'assets/icons'}),
LayoutModule,
NgbModule.forRoot()
],
})
.compileComponents();
}));
beforeEach(() => {
orderFormFetchService = TestBed.get(OrderFormFetchService);
fixture = TestBed.createComponent(OrderListComponent);
component = fixture.componentInstance;
orderListStub = [{
'id': '5c18e74dd5ab9332cc473c94',
'createdAt': '2018-12-18T12:25:49.507Z',
'updatedAt': '2018-12-18T12:25:49.507Z',
'name': 'apple',
'website': 'www.apple.com',
'secsId': ''
}];
spyOn(orderFormFetchService, 'getorders').and.returnValue(Observable.of(orderListStub));
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeDefined();
expect(component).toBeTruthy();
expect(fixture).toBeDefined();
expect(orderFormFetchService).toBeDefined();
});
it('check order list ', () => {
console.log(orderFormFetchService.getorders()); // -> undefined
expect(component.orderList).toBeDefined();
// expect(component.orderList).toEqual(orderListStub);
});
OrderListComponent 中的代码如下,
export class OrderListComponent extends BaseComponent implements OnInit {
defaultQuery = {website: null, name: null};
orderList: any;
query = _.clone(this.defaultQuery);
date: Date;
constructor(private orderFormFetchService: OrderFormFetchService) { super(); }
ngOnInit() {
this.date = new Date();
this.getOrderList();
}
getOrderList(): void {
this.orderFormFetchService.getOrders()
.subscribe((res: Response) => {
if (_.isArray(res)) {
this.orderList = _.orderBy(res, [order => order.name.toLowerCase()], ['asc']);
} else {
this.orderList = [res];
}
});
}
}
请帮忙