2016-12-06 80 views
3

我正在努力弄清楚如何将angular的激活路线存根到我的目的。在我的组成部分之一,我使用的路由快照得到激活路由的URL的一部分:Stub ActivatedRoute在Angular 2中的测试

let activatedPath = this.route.snapshot.children[0].url[0].path; 

在我的测试中,我发现了错误:

Error: Error in :0:0 caused by: undefined is not an object (evaluating 'this.route.snapshot.children[0].url')​​ 

所以我想我需要存根激活路线:

class FakeActivatedRoute { 
    // stub detail goes here 
} 

,并在我的测试为它提供:

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

任何人都可以提供任何指导方面的存根实施,让我去.snapshot.children[0].url[0].path?我目前毫无进展迅速:-)

+0

搜索[angular testing guide]上的'ActivatedRoute'(https://angular.io/docs/ts/latest/guide/testing.html)。有一个存根的例子。但是,我正试图为自己实现它,但我不知道如何设置组件创建时的testParams _before_。也许我们可以互相帮助? :) – 27leaves

+0

我现在也有_how注入部分。它可以在提供程序中的'activatedRoute = new ActivatedRouteStub();'在beforeEach'和'{provide:ActivatedRoute,useValue:activatedRoute}'中使用。 我没有使用快照,所以我不能帮你解决这个问题,但我认为以此为出发点,它不应该那么难;) – 27leaves

+0

有关这方面的消息吗?我也在苦苦挣扎。 – Striped

回答

1

你应该能够做这样的事情:

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

这样,你所提供的是嘲笑activatedRoute对象将回答这个完全相同的层次结构。