我被卡住,並在單元測試Angular 4組件時不斷收到錯誤。Angular 4單元測試錯誤「TypeError:無法讀取未定義的屬性」訂閱「
這裏是我的組件:
訂單detail.component.ts
@Component({
selector: 'order-detail',
templateUrl: 'order-detail.component.html',
providers: [OrderService]
})
export class OrderDetailComponent implements OnInit {
private order: Order;
constructor(
private orderService: OrderService,
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.getOrder();
}
private getOrder(): void {
this.route.paramMap
.map((params: ParamMap) => {
if (+params.get('id') === 0) {
this.router.navigateByUrl('/404', {skipLocationChange: true});
}
return params;
})
.switchMap((params: ParamMap) => this.orderService.getOrder(+params.get('id')))
.subscribe((order: Order) => this.order = order);
}
}
這裏是一個服務:
order.service.ts
@Injectable()
export class OrderService {
private ordersUrl = `${environment.apiUrl}/orders/`;
constructor(private http: HttpClient) {}
getOrder(id: number): Observable<Order> {
return this.http.get(`${this.ordersUrl}${id}/`)
.map(response => response as Order);
}
}
我想設置OrderServive
和單位間諜與這樣的測試測試:
訂單detail.component.spec.ts
describe('Order detail component',() => {
let fixture: ComponentFixture<OrderDetailComponent>;
let page: Page;
let activatedRoute: ActivatedRouteStub;
const fakeOrder: Order = {
id: 1,
title: 'Test 1',
contractor: {title: 'Contractor 1'} as Contractor,
} as Order;
class Page {
orderSpy: jasmine.Spy;
routerSpy: jasmine.Spy;
title: HTMLElement;
constructor() {
const orderService = fixture.debugElement.injector.get(OrderService);
this.orderSpy = spyOn(orderService, 'getOrder').and.returnValue(Observable.of(fakeOrder));
}
}
function createComponent() {
fixture = TestBed.createComponent(OrderDetailComponent);
page = new Page();
fixture.detectChanges();
return fixture.whenStable().then(() => {
fixture.detectChanges();
});
}
beforeEach(() => {
activatedRoute = new ActivatedRouteStub();
});
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [OrderDetailComponent],
imports: [RouterTestingModule, HttpClientTestingModule],
providers: [
OrderService,
{provide: ActivatedRoute, useValue: activatedRoute},
{provide: Router, useClass: RouterStub},
],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
}));
describe('when navigate with existing id',() => {
beforeEach(async(() => {
activatedRoute.testParamMap = {id: fakeOrder.id};
createComponent();
}));
it('should show title',() => {
expect(page.orderSpy).toHaveBeenCalledWith(fakeOrder.id);
});
});
});
但我不斷收到此錯誤:TypeError: Cannot read property 'subscribe' of undefined
我把ActivatedRouteStub
和測試結構從Agular文檔:https://angular.io/guide/testing
組件的代碼工作正常與後端的真實數據並顯示我的順序。
另外我的代碼庫包含類似的測試,它在另一個具有類似服務的組件上成功地做了同樣的事情,所以這個測試是唯一失敗的地方。
使用Angular 4.3.6,Karma 1.7.1和Jasmine 2.6.4。
什麼可能出錯,以及如何擺脫這個錯誤?