【问题标题】:Angular - Testing routing with back navigationAngular - 使用返回导航测试路由
【发布时间】: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


【解决方案1】:

我有同样的问题,也不知道。所以我开始深入研究RouterTestingModule 如何在您的用例中设置两个最重要的“组件”:RouterLocation

使用过的路由器是真实的,但它被交给了SpyLocation。所以我认为它只是伪造 popstate 并且不会以任何方式修改路由器状态,但它实际上具有与真实 Location 相同的副作用 - 它发出一个事件(在您的情况下为 popstate)。现在Router不管 Location 实现,通过调用它的setUpLocationChangeListener订阅这些事件,当像 popstate 这样的事件发生时,它会在它的routerState。我发现,在我的测试用例中,显然在你的测试用例中,事件订阅没有被创建,因为这个方法没有被调用。

解决方案很简单。在测试任何 popstate 代码之前,您必须调用 router.initialNavigation()。理想情况下,您将其作为路由器上的第一个操作。因为,正如您在下面看到的(这是唯一完成此操作的地方)位置更改侦听器设置在那里。

来自router.ts

initialNavigation(): void {
    this.setUpLocationChangeListener();                                                                                                                                                                                                                                            
    if (this.navigationId === 0) {
        this.navigateByUrl(this.location.path(true), {replaceUrl: true})      
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    相关资源
    最近更新 更多