I have to implement ngrx/store (Version 4.0.3) in an existing angular (Version 4.3.3) application.
I have problems to test a component because of this error message:
TypeError: undefined is not an object (evaluating 'state.search.results')
After reading this document Providing Store for testing I thought the implementation should be easy.
In my spec file I imported the StoreModule in the beforeEach method:
StoreModule.forRoot ({reducers}),
...
store = TestBed.get (Store);
spyOn (store, 'dispatch').and.callThrough ();
The reducer looks like:
import * as fromSearch from './search/search-reducer';
export interface State {
search: fromSearch.State;
}
export const reducers = {
search: fromSearch.reducer
};
and here the search-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;
}
}
}
In a method of the component I dispatch the specific action in a subscribe of a search service method (HTTP request):
this._searchService.search (query).subscribe (results => {
this._store.dispatch (new SearchActions.SearchSuccess (results.data));
});
In the spec file, the search service is a mock service.
After reading a lot of answers on this site I tried to dispatch the specific action in the beforeEach method to initialize the state.search.results
state. But I got the same error message.
How do I solve this state problem?
Thanks in advance.