所以我试图为这个组件创建一个单元测试并继续得到错误。 TypeError:无法读取属性' subscribe'未定义的。这是什么原因以及如何正确实现此组件的单元/集成测试?
边栏项-component.html
<a class="item"
[ngClass]="{ active: isActive() }"
[routerLink]="[item.path]">
{{ item.label }}
</a>
边栏项-component.ts
import {
Component,
OnInit,
Input
} from '@angular/core';
import { ExampleDef } from '../example.model';
import { Location } from '@angular/common';
import {
Router,
ActivatedRoute
} from '@angular/router';
@Component({
selector: 'app-sidebar-item',
templateUrl: './sidebar-item.component.html'
})
export class SidebarItemComponent implements OnInit {
@Input('item') item: ExampleDef;
constructor(private router: Router,
private route: ActivatedRoute,
private location: Location) {
}
// Checks if this current example is the selected one
isActive(): boolean {
return `/${this.item.path}` === this.location.path();
}
ngOnInit() {
}
}
规范文件
import { IntroComponent } from './../intro/intro.component';
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { SidebarItemComponent } from './sidebar-item.component';
import { Router, ActivatedRoute} from '@angular/router';
import { By } from '@angular/platform-browser';
import { RouterTestingModule } from '@angular/router/testing';
import { NgClass, Location } from '@angular/common';
import { SidebarComponent } from './sidebar.component';
import { ExampleDef } from '../example.model';
class RouterStub {
}
class ActivatedRouteStub {
}
class LocationStub {
}
class IntroComponentStub {
}
describe('sidebarItem component', () => {
let component: SidebarItemComponent;
let fixture: ComponentFixture<SidebarItemComponent>;
let router : Router;
let route: ActivatedRoute;
let location: Location;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes(routes)],
declarations: [ SidebarItemComponent],
providers: [ {provide: Router, useClass: RouterStub},
{provide: Location, useClass: LocationStub},
{provide: ActivatedRoute, useClass: ActivatedRouteStub},
{provide: IntroComponent, useClass: IntroComponentStub}]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SidebarItemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('should link to the item path', () => {
component.item.path = '/home';
component.item.label = 'Intro';
component.isActive();
fixture.detectChanges();
let de = fixture.debugElement.query(By.css('.item'))
let el: HTMLElement = de.nativeElement;
expect(el.innerText).toContain('intro');
});
});