【发布时间】:2017-11-08 09:58:35
【问题描述】:
我正在尝试在 Angular 应用程序中测试路由。我可以成功测试前进导航,但我无法测试后退导航。
我的测试规范:
import {Location} from "@angular/common";
import {TestBed, fakeAsync, tick} from '@angular/core/testing';
import {RouterTestingModule} from "@angular/router/testing";
import {Router} from "@angular/router";
import {
HomeComponent,
SearchComponent,
AppComponent,
routes
} from "./router"
describe('Router: App', () => {
let location: Location;
let router: Router;
let fixture;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ RouterTestingModule.withRoutes(routes)],
declarations: [
HomeComponent,
SearchComponent,
AppComponent
]
});
router = TestBed.get(Router);
location = TestBed.get(Location);
fixture = TestBed.createComponent(AppComponent);
});
it('location.back()', fakeAsync(() => {
router.navigate(['']);
tick();
expect(router.routerState.snapshot.url).toBe('/home');
router.navigate(['/search']);
tick();
expect(router.routerState.snapshot.url).toBe('/search');
console.log('BACK')
location.back()
tick();
expect(location.path()).toBe('/home');
expect(router.routerState.snapshot.url).toBe('/home');
}));
});
当使用router.navigate() 时,routerState 会更新(我还检查了router.events 发送导航事件)。但是,当调用location.back() 时,路由器状态没有更新,我通过router.events 没有收到任何路由器事件。
在 Angular 中使用后退(和前进)导航来测试代码的首选方法是什么?
提前致谢。
【问题讨论】:
-
有解决办法吗?
-
知道了@CularBytes
标签: angular testing location router back