Angular 2 测试中的存根 ActivatedRoute

zpy*_*dee 4 angular2-routing angular

我正在努力弄清楚如何存根 angular 的激活路线以满足我的目的。在我的一个组件中,我使用路由快照来获取激活路由的 url 的一部分:

let activatedPath = this.route.snapshot.children[0].url[0].path;
Run Code Online (Sandbox Code Playgroud)

在我的测试中,我收到错误:

Error: Error in :0:0 caused by: undefined is not an object (evaluating 'this.route.snapshot.children[0].url')??
Run Code Online (Sandbox Code Playgroud)

所以我想我需要存根 Activated 路线:

class FakeActivatedRoute {
    // stub detail goes here
}
Run Code Online (Sandbox Code Playgroud)

并在我的测试中提供它:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [
        SiteAdminComponent
      ],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        { provide: ActivatedRoute, useClass: FakeActivatedRoute }
      ]
    })
     .compileComponents();
}));
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供有关允许我到达的存根实现的任何指导.snapshot.children[0].url[0].path吗?我目前一无所获:-)

pin*_*oyd 5

您应该能够执行以下操作:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [
        SiteAdminComponent
      ],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        { 
          provide: ActivatedRoute, 
          useValue: {snapshot: {children: [{url: ['your/path/here']}]}} 
        }
      ]
    })
     .compileComponents();
}));
Run Code Online (Sandbox Code Playgroud)

这样你就提供了一个模拟的 activateRoute 对象,它将回答这个完全相同的层次结构。