Angular 2最终释放路由器单元测试

xph*_*ong 28 javascript karma-jasmine angular2-routing angular2-testing angular

如何使用karma和jasmine对Angular 2.0.0版中的路由器进行单元测试?

这是我的旧单元测试在版本2.0.0-beta.14中的样子

import {
  it,
  inject,
  injectAsync,
  beforeEach,
  beforeEachProviders,
  TestComponentBuilder
} from 'angular2/testing';

import { RootRouter } from 'angular2/src/router/router';
import { Location, RouteParams, Router, RouteRegistry, ROUTER_PRIMARY_COMPONENT } from 'angular2/router';
import { SpyLocation } from 'angular2/src/mock/location_mock';
import { provide } from 'angular2/core';

import { App } from './app';

describe('Router', () => {

  let location, router;

  beforeEachProviders(() => [
    RouteRegistry,
    provide(Location, {useClass: SpyLocation}),
    provide(Router, {useClass: RootRouter}),
    provide(ROUTER_PRIMARY_COMPONENT, {useValue: App})
  ]);

  beforeEach(inject([Router, Location], (_router, _location) => {
    router = _router;
    location = _location;
  }));

  it('Should be able to navigate to Home', done => {
    router.navigate(['Home']).then(() => {
      expect(location.path()).toBe('');
      done();
    }).catch(e => done.fail(e));
  });

});
Run Code Online (Sandbox Code Playgroud)

Pau*_*tha 82

为了测试,我们现在使用创建测试模块TestBed.我们可以使用TestBed#configureTestingModule和传递元数据对象,就像我们传递给它一样@NgModule

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [ /* modules to import */ ],
    providers: [ /* add providers */ ],
    declarations: [ /* components, directives, and pipes */ ]
  });
});
Run Code Online (Sandbox Code Playgroud)

对于路由,RouterModule我们宁愿使用,而不是使用正常RouterTestingModule.这将设置RouterLocation,这样你就不需要自己.您也可以通过呼叫将路由传递给它RouterTestingModule.withRoutes(Routes)

TestBed.configureTestingModule({
  imports: [
    RouterTestingModule.withRoutes([
      { path: 'home', component: DummyComponent }
    ])
  ]
})
Run Code Online (Sandbox Code Playgroud)

为了得到Location并且Router在测试中,同样的事情起作用,如在你的例子中.

let router, location;

beforeEach(() => {
  TestBed...
});

beforeEach(inject([Router, Location], (_router: Router, _location: Location) => {
  router = _router;
  location = _location;
}));
Run Code Online (Sandbox Code Playgroud)

您也可以根据需要注入每个测试

it('should go home',
    async(inject([Router, Location], (router: Router, location: Location) => {
})));
Run Code Online (Sandbox Code Playgroud)

async上述用于像done除了我们并不需要显式调用done.在所有异步任务完成后,Angular实际上会为我们做这件事.

获得提供者的另一种方法是从试验台.

let location, router;

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [RouterTestingModule.withRoutes([
      { path: 'home', component: DummyComponent }
    ])],
  });
  let injector = getTestBed();
  location = injector.get(Location);
  router = injector.get(Router);
});
Run Code Online (Sandbox Code Playgroud)

这是一个完整的测试,重构你的例子

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

@Component({
  template: `
    <router-outlet></router-outlet>
  `
})
class RoutingComponent { }

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

describe('component: RoutingComponent', () => {
  let location, router;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes([
        { path: 'home', component: DummyComponent }
      ])],
      declarations: [RoutingComponent, DummyComponent]
    });
  });

  beforeEach(inject([Router, Location], (_router: Router, _location: Location) => {
    location = _location;
    router = _router;
  }));

  it('should go home', async(() => {
    let fixture = TestBed.createComponent(RoutingComponent);
    fixture.detectChanges();
    router.navigate(['/home']).then(() => {
      expect(location.path()).toBe('/home');
      console.log('after expect');
    });
  }));
});
Run Code Online (Sandbox Code Playgroud)

UPDATE

此外,如果你想简单地模拟路由器,这实际上可能是进行单元测试的更好方法,你可以简单地做

let routerStub;

beforeEach(() => {
  routerStub = {
    navigate: jasmine.createSpy('navigate'),
  };
  TestBed.configureTestingModule({
    providers: [ { provide: Router, useValue: routerStub } ],
  });
});
Run Code Online (Sandbox Code Playgroud)

在测试中,您要做的就是测试在组件与之交互时使用正确的参数调用存根

expect(routerStub.navigate).toHaveBeenCalledWith(['/route']);
Run Code Online (Sandbox Code Playgroud)

除非你真的想测试一些路由,否则这可能是首选的方法.无需设置任何路由.在单元测试中,如果您使用实际路由,则会涉及不必要的副作用,这可能会影响您实际尝试测试的内容,这只是组件的行为.而组件的行为就是简单地调用该navigate方法.它不需要测试路由器的工作原理.Angular已经保证了这一点.

  • 请注意,使用angular2版本2.4.9,你需要在mock中使用`routerState`:`routerStub = {navigate:...,routerState:{}}`,否则你会收到错误.另外,当使用`useFactory`进行模拟时,必须像这样写:`useFactory:function(){...}`,而不是'useFactory :()=> {...}`,否则会发生另一个错误. (3认同)
  • 语法错误纠正:`{提供:路由器,useValue:routerStub}`,`expect(routerStub.navigate).toHaveBeenCalledWith(['/ route']);` (2认同)
  • 当我这样做时,它说:TypeError:无法读取未定义的属性“ root” (2认同)