2017-06-05 49 views
1

我有兩個文件:x.component和x.service如何獲得商店並指定爲窺探可變

x.service.ts

store$: Store<DogsStore>; 

constructor(private store: Store<DogsStore>) { 
    this.store$ = store; 
} 

x.component.ts

constructor(private xService: X) {} 

ngOnInit() { 
    this.xService.store$.select('something').subscribe(...) 
} 

測試x.component我收到一個錯誤cannot subscribe of undefined。在x.spec.ts我使用x.service.spy.ts在那裏我有

store$: Store<DogsStore>; 

,你可以看到,因爲我不能使用類似store$: Store<DogsStore> = new Store()我沒有初始化。我如何獲得商店並將其分配給變量?也許還有其他問題要做?

回答

1

如果我有問題吧,這裏是如何做到這一點:

基本上,你的應用程序模塊提供了店,但測試沒有。因此,在你規範文件,該beforeEach的一部分,應該通過導入它提供它:

TestBed.configureTestingModule({ 
     imports: [ 
     SomeModule, 
     StoreModule.provideStore(reducer), // or your reducer name 
     .... 
     ], 
     .... 
    }); 

,然後(在beforeEach通話仍然)就可以窺探:

spyOn(getTestBed().get(Store), 'dispatch').and.callThrough(); 

這樣您的組件將獲得它。

我們可以訪問到調度包裝,你應該在測試中注入它:

it('test something', inject([Type1, Type2, Store], 
    (dep1: Type1, dep2: Type2, store) => { 
     expect(store.dispatch.calls.count()).toEqual(<count_value>); 
    } 

現在請注意,在我離開店無類型的方法簽名,這是因爲否則靜態檢查抱怨store.dispatch有沒有會員calls