2017-10-19 192 views
3

在我的角4分I有類似:如何模擬route.snapshot.params?

constructor(private route: ActivatedRoute) { 
} 

ngOnInit() { 
    this.myId = this.route.snapshot.params['myId']; 
} 

我試圖創建一個假設看起來像遵循模擬:

class MockActivatedRoute extends ActivatedRoute { 
    public params = Observable.of({ myId: 123 }); 
}  

我的測試失敗:

TypeError: Cannot read property 'params' of undefined.

我該如何嘲笑它?我誤解了ActivatedRoute的正確用法,並且最好在我的組件中使用router.subscribe?我看到一些複雜的例子,人們嘲笑快照本身,但對我來說,它看起來過於複雜。

+0

我也試圖做類似'常量fakeRoutes:路線= {[路徑: '信息',數據:{採用catalogId: '123'} ,component:StatusComponent},]'然後'RouterTestingModule.withRoutes(fakeRoutes)'。不確定這個語法是否被支持。 – and85

+0

你想在單元測試中使用它嗎?如果是的話,你可以發佈代碼 – LLai

+0

你會得到未定義的參數,因爲你的模擬是嘲諷可觀察的'this.route.params'(返回一個可觀察的)而不是快照'this.route.snapshot.params'(返回一個對象的參數) – LLai

回答

1

測試本身是很簡單的:

describe('ngOnInit',() => { 
it('should set up initial state properly', 
() => { 
    const component = TestBed.createComponent(MyComponent).componentInstance; 
    component.ngOnInit(); 
    expect(component.myId).toEqual('123'); 
    }); 
}); 

如果我只是測試下,改變方法類似如下 - 測試工作:

ngOnInit() { 
    //this.myId = this.route.snapshot.params['myId']; 
    this.route.params.subscribe(params => { 
    this.myId = params['myId']; 
    }); 
} 

很顯然,我需要模擬激活快照,但是有沒有更好的方法?

3

好的,我發現如何以簡單的方式模擬ActivatedRoute快照。這樣的事情對我的作品:

providers: [MyComponent, { 
    provide: ActivatedRoute, 
    useValue: {snapshot: {params: {'myId': '123'}}} 
} 

謝謝:)

+0

謝謝!!!!!!! –