我试图用angular 2 final测试我的组件,但我得到了一个错误,因为组件使用了routerLink指令.我得到以下错误:

无法绑定到"routerLink",因为它不是"a"的已知属性.

这是ListComponent模板的相关代码

<a 
  *ngFor="let item of data.list" 
  class="box"
  routerLink="/settings/{{collectionName}}/edit/{{item._id}}">

这是我的测试.

import { TestBed } from '@angular/core/testing';

import { ListComponent } from './list.component';
import { defaultData, collectionName } from '../../config';
import { initialState } from '../../reducers/reducer';


const data = {
  sort: initialState.sort,
  list: [defaultData, defaultData],
};

describe(`${collectionName} ListComponent`, () => {
  let fixture;
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        ListComponent,
      ],
    }).compileComponents(); // compile template and css;
    fixture = TestBed.createComponent(ListComponent);
    fixture.componentInstance.data = data;
    fixture.detectChanges();
  });

  it('should render 2 items in list', () => {
    const el = fixture.debugElement.nativeElement;
    expect(el.querySelectorAll('.box').length).toBe(3);
  });
});

我看了几个类似问题的答案,但找不到适合我的解决方案.

推荐答案

您需要配置所有路由.对于测试,您可以使用@angular/router/testing中的RouterTestingModule,而不是RouterModule,在这里您可以设置一些模拟路由.您还需要将CommonModule@angular/common导入*ngFor.下面是一个完整的通过测试

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { By } from '@angular/platform-browser';
import { Location, CommonModule } from '@angular/common';
import { RouterTestingModule } from '@angular/router/testing';
import { TestBed, inject, async } from '@angular/core/testing';

@Component({
  template: `
    <a routerLink="/settings/{{collName}}/edit/{{item._id}}">link</a>
    <router-outlet></router-outlet>
  `
})
class TestComponent {
  collName = 'testing';
  item = {
    _id: 1
  };
}

@Component({
  template: ''
})
class DummyComponent {
}

describe('component: TestComponent', function () {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        RouterTestingModule.withRoutes([
         { path: 'settings/:collection/edit/:item', component: DummyComponent }
        ])
      ],
      declarations: [ TestComponent, DummyComponent ]
    });
  });

  it('should go to url',
    async(inject([Router, Location], (router: Router, location: Location) => {

    let fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();

    fixture.debugElement.query(By.css('a')).nativeElement.click();
    fixture.whenStable().then(() => {
      expect(location.path()).toEqual('/settings/testing/edit/1');
      console.log('after expect');
    });
  })));
});

使现代化

另一个选项是,如果您只想测试路由是否正确呈现,而不需要try 导航...

您只需导入RouterTestingModule个,无需配置任何路由

imports: [ RouterTestingModule ]

然后只需判断链接是否以正确的URL路径呈现,例如.

let href = fixture.debugElement.query(By.css('a')).nativeElement
    .getAttribute('href');
expect(href).toEqual('/settings/testing/edit/1');

Typescript相关问答推荐

如何正确修复TypScript 4.7到4.8升级中的TS 2345编译错误

在React中实现具有独立页面的嵌套路径的最佳实践是什么?

typescript抱怨值可以是未定义的,尽管类型没有定义

为什么typescript要把这个空合并转换成三元?

类型脚本接口索引签名

为什么TypeScript假设文档对象始终可用?

类型{}上不存在属性&STORE&A;-MobX&A;REACT&A;TYPE脚本

状态更新后未触发特定元素的Reaction CSS转换

类型脚本返回的类型包含无意义的泛型类型名称

了解类型规则中的关键字

在HighChats列时间序列图中,十字准线未按预期工作

Angular material 无法显示通过API获取的数据

try 使Angular依赖注入工作

如何键入并类型的函数&S各属性

扩展对象的此内容(&Q;)

可以将JS文件放在tsconfig';s includes/files属性?或者,我如何让tsc判断TS项目中的JS文件?

如何正确键入泛型相对记录值类型?

从泛型对象数组构造映射类型

如何在Typescript 中定义具有相同类型的两个泛型类型的两个字段?

基于泛型类型的条件类型,具有条目属性判断