Skip to content

Commit

Permalink
fix(store): call metareducer with the user's config initial state
Browse files Browse the repository at this point in the history
  • Loading branch information
itay committed Jan 4, 2019
1 parent 37e4f69 commit 6c801b1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
30 changes: 25 additions & 5 deletions modules/store/spec/store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -534,24 +534,44 @@ describe('ngRx Store', () => {
expect(metaReducerSpy2).toHaveBeenCalled();
});

it('should create a meta reducer for feature and call it with the expected reducer', () => {
it('should create a meta reducer for feature and call it with the expected reducer', done => {
const counterReducer2Spy = jasmine
.createSpy('counterReducer2Spy', counterReducer2)
.and.callThrough();

TestBed.configureTestingModule({
imports: [
StoreModule.forRoot({}),
StoreModule.forFeature('counter1', counterReducer, {
metaReducers: [metaReducerContainer.metaReducer1],
}),
StoreModule.forFeature('counter2', counterReducer2, {
metaReducers: [metaReducerContainer.metaReducer2],
}),
StoreModule.forFeature(
'counter2',
{ counter: counterReducer2Spy },
{
initialState: { counter: 2 },
metaReducers: [metaReducerContainer.metaReducer2],
}
),
],
});

const mockStore = TestBed.get(Store);
const action = { type: INCREMENT };

mockStore.dispatch(action);

expect(metaReducerSpy1).toHaveBeenCalledWith(counterReducer);
expect(metaReducerSpy2).toHaveBeenCalledWith(counterReducer2);
expect(metaReducerSpy2).toHaveBeenCalled();
expect(counterReducer2Spy).toHaveBeenCalledWith(2, action);

mockStore.pipe(take(1)).subscribe({
next(val: any) {
expect(val['counter2'].counter).toEqual(3);
},
error: done,
complete: done,
});
});
});

Expand Down
12 changes: 10 additions & 2 deletions modules/store/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
ActionReducerFactory,
ActionReducerMap,
MetaReducer,
InitialState,
} from './models';

export function combineReducers<T, V extends Action = Action>(
Expand Down Expand Up @@ -92,10 +93,17 @@ export function createReducerFactory<T, V extends Action = Action>(
metaReducers?: MetaReducer<T, V>[]
): ActionReducerFactory<T, V> {
if (Array.isArray(metaReducers) && metaReducers.length > 0) {
return compose.apply(null, [...metaReducers, reducerFactory]);
reducerFactory = compose.apply(null, [...metaReducers, reducerFactory]);
}

return reducerFactory;
return (rm: ActionReducerMap<T, V>, initialState?: InitialState<T>) => {
const reducer = reducerFactory(rm, initialState);

return (state: T | undefined, action: V) => {
state = state === undefined ? (initialState as T) : state;
return typeof reducer === 'function' ? reducer(state, action) : state;
};
};
}

export function createFeatureReducerFactory<T, V extends Action = Action>(
Expand Down

0 comments on commit 6c801b1

Please sign in to comment.