[英]angular / ngrx store 4: Uninitialize state in component test
我必須在現有的angular(版本4.3.3)應用程序中實現ngrx / store(版本4.0.3)。
由於此錯誤消息,我在測試組件時遇到問題:
TypeError: undefined is not an object (evaluating 'state.search.results')
閱讀了此文件提供測試商店之后,我認為實現應該很容易。
在我的規格文件中,我以beforeEach方法導入了StoreModule:
StoreModule.forRoot ({reducers}),
...
store = TestBed.get (Store);
spyOn (store, 'dispatch').and.callThrough ();
減速器看起來像:
import * as fromSearch from './search/search-reducer';
export interface State {
search: fromSearch.State;
}
export const reducers = {
search: fromSearch.reducer
};
這里是搜索減少器:
export interface State {
searchTerms: string;
results: [];
limit: SearchLimit;
}
// Imported: initialState & initalSearchLimitState
const initialState: State = {
searchTerms: '',
results: [initialState],
limit: initalSearchLimitState
};
export function reducer (state = initialState, action: SearchActions.All): State {
switch (action.type) {
case SearchActions.SEARCH: {
return {
...state,
searchTerm: action.payload
};
}
case SearchActions.SEARCH_SUCCESS: {
return {
...state,
results: action.payload
};
}
case SearchActions.SEARCH_LIMIT_EXCEEDED: {
return {
...state,
limit: action.payload
};
}
default: {
return state;
}
}
}
在該組件的方法中,我以訂閱搜索服務方法(HTTP請求)的方式調度特定操作:
this._searchService.search (query).subscribe (results => {
this._store.dispatch (new SearchActions.SearchSuccess (results.data));
});
在規格文件中,搜索服務是模擬服務。
在此站點上閱讀了很多答案之后,我嘗試在beforeEach方法中調度特定操作以初始化state.search.results
狀態。 但是我得到了同樣的錯誤信息。
我該如何解決此狀態問題?
提前致謝。
我找到了解決我問題的方法。
我從
export const reducers
至
export const reducers: ActionReducerMap<State>
此外,我已經在beforeEach方法的import數組中添加了初始狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.