我正在尝试在Angular 2.2.1中测试我的路由器,以确保设置正确的路由并转到预期的位置。我已完成Google研究,已阅读并重新阅读https://angular.io/docs/ts/latest/guide/testing.html示例中的app.component.router.spec.ts文件,但仍然不足。
我在这里找到了一个非常好的答案,这个答案很容易理解并且显而易见: Angular 2 Final Release Router Unit Test
所以使用它,我创建了它作为我自己的路由器的测试:
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 },
{ path: 'not-exists', component: DummyComponent }
])],
declarations: [RoutingComponent, DummyComponent]
});
});
beforeEach(inject([Router, Location], (_router: Router, _location: Location) => {
location = _location;
router = _router;
}));
it('should fail, but does not', async(() => {
let fixture = TestBed.createComponent(RoutingComponent);
fixture.detectChanges();
router.navigate(['not-exists']).then(() => {
expect(location.path()).toBe('/not-exists');
console.log('after expect');
});
}));
});
我遇到的问题是我不明白这是如何测试我的真实路由器的。正如您所看到的,我在这里创建了一个名为“not-exists”的路径,该路径转到虚拟组件,并且如名称所示,此路由在我的真实路由器中不存在。这让我相信除了我放在这里的路径之外,它确实没有测试任何东西。
所以我的问题是:
谢谢!