【问题标题】:Unit testing RouterLink in Angular2 component在 Angular2 组件中对 RouterLink 进行单元测试
【发布时间】:2017-01-22 16:34:33
【问题描述】:

我正在尝试在我的组件中测试对 routerLink 的点击:

  <div class="side-menu-boards-container">
    <ul class="side-menu-boards-list">
      <li *ngFor="let board of boards">
        <a [routerLink]="['/board', board.id]">{{board.name}}</a>
      </li>
    </ul>
  </div>

使用这个测试:

it('should navigate to correct board url',
    async(inject([Location], (location: Location) => {
      let nativeElement = fixture.nativeElement;
      let link = nativeElement.querySelector('.side-menu-boards-list li a');
      link.click();

      fixture.whenStable().then(() => {
        expect(location.path()).toEqual('/board/1');
      });    
})));

但我的期望失败并显示以下消息:Expected '/' to equal '/board/1'

这是我的测试设置:

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

import { SideMenuComponent } from './side-menu.component';
import { BoardComponent } from '../board/board.component';
import { BoardMenuItem } from './models/board-menu-item';

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

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [SideMenuComponent, BoardComponent],
      schemas: [NO_ERRORS_SCHEMA],
      imports: [RouterTestingModule.withRoutes([
        { path: 'board/:id', component: BoardComponent }
      ])]
    })
      .compileComponents();
  });

我已经关注了其他两个与 SO 相关的问题(herehere)的答案,但无济于事。

关于我做错了什么有什么想法吗?

【问题讨论】:

    标签: angular routerlink


    【解决方案1】:

    如果您使用外部模板,我建议您异步创建组件。

    我建议的第二件事是尝试使用RouterTestingModule.withRoutes(&lt;your routes module&gt;) 来测试路由器。

    并且不要忘记初始导航。

    beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports:[RouterTestingModule.withRoutes(routes),
                   <Another Modules>, 
                    ],
          declarations: [ <your component>],
          providers: [<Services which you have injected inside of your constructor>]
        })
        .compileComponents()
        .then(() =>{
              fixture = TestBed.createComponent(<your component>);
              component = fixture.componentInstance;
              router = TestBed.get(Router);
              location = TestBed.get(Location);
              debugComponent = fixture.debugElement;
              //initial navigation
              router.initialNavigation();
        });
    }));
    

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 1970-01-01
      • 2016-10-19
      • 2016-03-13
      • 2017-04-14
      • 2017-01-27
      • 1970-01-01
      • 2017-05-13
      • 2017-02-03
      相关资源
      最近更新 更多