Angular RouterStub:返回url属性

时间:2017-07-10 20:38:43

标签: angular unit-testing

我的方法navigate有一个路由器存根,代码如下:

@Injectable()
export class RouterStub {
    public events: any;

    public setRoutesRecognized(routesRecognized: RoutesRecognized) {
      this.events = new Observable(observer => {
        observer.next(routesRecognized);
        observer.complete();
      });
    }

    public navigate(commands: any[], extras?: NavigationExtras) { }
}

我需要返回导航的URL。通过嘲笑Angular中的内容,我真的很难过。

例如,我必须遍历项目并检查URL:

private selectTabBasedOnActiveRoute() {
    for (let i = 0; i < this.tabs.length; i++) {
      if (this.router.url.indexOf(this.tabs[i].url) > 0) {
          this.selectedTabIndex = i;
      }
    }
}

这是我的测试:

beforeEach(() => {
    activatedRouteStub = new ActivatedRouteStub();
    activatedRouteStub.testParamMap = { customerId: 1 };

    routerStub = new RouterStub();

    TestBed.configureTestingModule({
      imports: [
        ContractModule,
        RouterTestingModule.withRoutes(contractRoutes)
      ],
      providers: [
        { provide: Router, useValue: routerStub },
        { provide: ActivatedRoute, useValue: activatedRouteStub } ]
    });

    fixture = TestBed.createComponent(ContractTabListComponent);
    component = fixture.componentInstance;

    service = fixture.debugElement.injector.get(ContractService);
});

it("should select 'Customer' tab when navigating to empty route", fakeAsync(() => {
    // Act
    routerStub.navigate([""]);

    fixture.detectChanges(); // this calls selectTabBasedOnActiveRoute

    tick();

    // Assert
    expect(component.selectedTabIndex).toBe(0);
}));

如何从 RouterStub 返回this.router.url

我错过了什么?

修改

我正在分享我现在所做的事情。我不知道它是否正确,因为我没有找到任何参考:

@Injectable()
export class RouterStub {
  public events: any;

  public url;

  public setRoutesRecognized(routesRecognized: RoutesRecognized) {
    this.events = new Observable(observer => {
      observer.next(routesRecognized);
      observer.complete();
    });
  }

  public navigate(commands: any[], extras?: NavigationExtras) {
    this.url = commands[0];
  }
}

0 个答案:

没有答案