角度2单元测试组件与routerLink

前端之家收集整理的这篇文章主要介绍了角度2单元测试组件与routerLink前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图用角2测试我的组件,但是我收到一个错误,因为组件使用了routerLink指令.我收到以下错误

Can’t bind to ‘routerLink’ since it isn’t a known property of ‘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);
  });
});

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

您需要配置所有路由.对于测试而不是使用RouterModule,您可以使用@ angular / router / testing中的RouterTestingModule,您可以在其中设置一些模拟路由.您还需要从*角度/常用的* ngFor导入CommonModule.下面是一个完整的通过测试
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');
    });
  })));
});

UPDATE

另一个选项,如果您只想测试路线是否正确呈现,而不尝试浏览…

您只需导入RouterTestingModule而不配置任何路由

imports: [ RouterTestingModule ]

然后检查链接是否以正确的URL路径呈现,例如

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

猜你在找的Angularjs相关文章