使用routerLink进行Angular 2单元测试组件

sel*_*ect 55 typescript angular2-routing angular2-testing angular

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

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

这是ListComponent模板的相关代码

<a 
  *ngFor="let item of data.list" 
  class="box"
  routerLink="/settings/{{collectionName}}/edit/{{item._id}}">
Run Code Online (Sandbox Code Playgroud)

这是我的考验.

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*tha 97

您需要配置所有路由.对于测试,RouterModule您可以使用RouterTestingModulefrom ,而不是使用from @angular/router/testing,您可以在其中设置一些模拟路由.您还需要导入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');
    });
  })));
});
Run Code Online (Sandbox Code Playgroud)

UPDATE

另一种选择,如果你只想测试路线是否正确渲染,而不试图导航......

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

imports: [ RouterTestingModule ]
Run Code Online (Sandbox Code Playgroud)

然后只需检查链接是否使用正确的URL路径进行渲染,例如

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


mah*_*lst 22

如果您没有测试路由器相关的东西,您可以配置测试以忽略带有'NO_ERRORS_SCHEMA'的未知指令

 import { NO_ERRORS_SCHEMA } from '@angular/core';
 TestBed.configureTestingModule({
   declarations: [
     ListComponent,
   ],
   schemas: [ NO_ERRORS_SCHEMA ]
 });
Run Code Online (Sandbox Code Playgroud)

  • @CalvinDale那应该没关系.很多东西都标有实验性(包括像Http这样常用的类).https://angular.io/docs/ts/latest/api/#!?status=experimental (2认同)

Anu*_*sht 6

为编写测试用例routerLink。您可以按照以下步骤操作。

  1. 导入RouterTestingModuleRouterLinkWithHref

    import { RouterTestingModule } from '@angular/router/testing';
    import { RouterLinkWithHref } from '@angular/router';
    
    Run Code Online (Sandbox Code Playgroud)
  2. 导入RouterTestingModule模块

    TestBed.configureTestingModule({
      imports: [ RouterTestingModule.withRoutes([])],
      declarations: [ TestingComponent ]
    })
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在测试用例中,找到要RouterLinkWithHref测试的链接的指令tot。

    it('should have a link to /', () => {
      const debugElements = fixture.debugElement.queryAll(By.directive(RouterLinkWithHref));
      const index = debugElements.findIndex(de => {
        return de.properties['href'] === '/';
      });
      expect(index).toBeGreaterThan(-1);
    });
    
    Run Code Online (Sandbox Code Playgroud)

  • 导入工作也作为`imports: [ RouterTestingModule ]` (2认同)