Angular路由器链接适用于ng服务,但在运行单元测试时,例如ng test我得到以下错误。
这是我在html中的链接:
<a [routerLink]="['/about']" class="button large" [myHighlight]="'gold'" title="About">About</a>
这是错误消息:
错误:模板解析错误:无法绑定到'routerLink' 不是'a'的已知属性。
这是此组件的模块:
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { RouterModule } from "@angular/router";
import { FormsModule} from "@angular/forms";
import { HomeComponent } from "./home.component";
import { UserService } from "../../services/user.service";
import { HighlightDirective } from "../../directives/highlight.directive";
@NgModule({
imports: [CommonModule, RouterModule, FormsModule],
declarations: [HomeComponent, HighlightDirective],
exports: [HomeComponent],
providers: [UserService]
})
export class HomeModule {
}
导入了RouterModule,因此不确定为什么单元测试不满意。
这是我对该组件的单元测试:
import { TestBed, async, inject } from "@angular/core/testing";
import { Observable } from "rxjs/Observable";
import { of } from 'rxjs/observable/of';
import { HttpClient, HttpHandler } from "@angular/common/http";
import { RouterModule } from "@angular/router";
import { Router } from '@angular/router';
import { HomeComponent } from "./home.component";
import { UserService } from "../../services/user.service";
import { User } from "../../models/user.model";
import { HighlightDirective } from "../../directives/highlight.directive";
class RouterStub {
navigateByUrl(url: string) { return url; }
}
describe("HomeComponent", () => {
let userService;
let homeComponent;
let fixture;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterModule],
declarations: [
HomeComponent,
HighlightDirective
],
providers: [
HttpClient,
HttpHandler,
UserService,
{ provide: Router, useClass: RouterStub }
]
});
});
beforeEach(inject([UserService], service => {
userService = service;
fixture = TestBed.createComponent(HomeComponent);
homeComponent = fixture.componentInstance;
}));
it("should return array of users as observable", async(() => {
// Arrange
const response: User[] = [];
spyOn(userService, "getUsers").and.returnValue(of(response));
// Act
homeComponent.getUsers();
fixture.detectChanges();
// Assert
expect(homeComponent.listOfUsers).toEqual(response);
}));
});
这是我的组成部分:
import { Component, OnInit, Output, EventEmitter } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Router } from '@angular/router';
import { UserService } from "../../services/user.service";
import { User } from "../../models/user.model";
@Component({
selector: "home-users",
templateUrl: "./home.component.html"
})
export class HomeComponent implements OnInit {
@Output() userEvent = new EventEmitter();
private listOfUsers: User[];
constructor(private userService: UserService, private router: Router) {}
// Lifecycle Hook (8 exist)
ngOnInit() {
this.getUsers();
}
getUsers(): void {
this.userService.getUsers().subscribe(users => {
this.listOfUsers = users;
this.userEvent.emit("getUsers - complete");
});
}
}
当前错误:
错误:没有ActivatedRoute的提供者!