Angular2单元测试错误:无法绑定到'routerLink',因为它不是'a'的已知属性

时间:2017-02-15 09:50:48

标签: angular

我正在尝试使用单元测试(karma,jasmine)进行管理,我收到了错误:

  

无法绑定到'routerLink',因为它不是'a'

的已知属性

我甚至没有更改由angular-cli ...

创建的* .spec.ts文件

以下是我的文件:

用户-list.component.html

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { IUser, User } from '../../../interfaces/user';
import { UsersService } from '../../../services/users.service';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.css']
})
export class UsersListComponent implements OnInit {

  users: IUser[] = [];

  constructor(private usersService: UsersService, private router: Router) { }

  ngOnInit() {
    this.usersService.getAll()
      .subscribe(users => {
        this.users = users.sort(...).map(...);
      });

  }

  userClicked(user) {
    this.usersService.setCurrentUser(user);
  }

  clickXBtn(user) {
    this.usersService
        .deleteUser(user)
        .subscribe(...);
  }

}

用户-list.component.ts

/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { UsersListComponent } from './user-list.component';

describe('UsersListComponent', () => {
  let component: UsersListComponent;
  let fixture: ComponentFixture<UsersListComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ UsersListComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(UsersListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

用户-list.component.spec.ts

{{1}}

我应该改变什么?如何使它工作?

2 个答案:

答案 0 :(得分:4)

Angular 2 Jasmine Can't bind to 'routerLink' since it isn't a known property of 'a'

可能重复

要解决您的问题,请尝试存根RouterLink https://angular.io/docs/ts/latest/guide/testing.html#!#router-link-stub

@Directive({
  selector: '[routerLink]',
  host: {
    '(click)': 'onClick()'
  }
})
export class RouterLinkStubDirective {
  @Input('routerLink') linkParams: any;
  navigatedTo: any = null;

  onClick() {
    this.navigatedTo = this.linkParams;
  }
}

在测试中使用存根的RouterLink

答案 1 :(得分:1)

RouterLink存根的更新版本为

import { Directive, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[routerLink]',
})
export class RouterLinkStubDirective {
  @Input('routerLink') linkParams: any;
  navigatedTo: any;

  @HostListener('click') onClick(): void {
    this.navigatedTo = this.linkParams;
  }
}

但是,存根代码不是必需的。 您需要做的就是将此语句添加到您的.spec.ts文件中

import { RouterTestingModule } from '@angular/router/testing';