测试 ngrx 元减速器

Testing ngrx meta reducers

我有一个应该在注销时清除状态的元减速器。

export function clearState(reducer: ActionReducer<any>): ActionReducer<any> {
  return (state, action) => {
    if (action.type === AuthActionTypes.UNAUTHENTICATED) {
      state = undefined;
    }
    return reducer(state, action);
  };
}

export const metaReducers: MetaReducer<any>[] = [clearState];

我想对这段代码进行单元测试。我之前测试过普通的 reducer,但对我来说,在为 meta reducer 编写测试时很难应用相同的技术。并且文档中没有示例。

这可能不是全部,但像这样的东西应该有用:

let store: Store<any>;
....
store = TestBed.inject(Store); // TestBed.inject is TestBed.get in older versions of Angular
TestBed.configureTEstingModule({
  imports: [StoreModule.forRoot(/* put your reducers here */, { metaReducers })],
});

it('should re-initialize the state once unauthenticated is dispatched', async () => {
   store.dispatch(/* dispatch an action that will change the store */);
   const newPieceOfState = await this.store.select(state => ...).pipe(take(1)).toPromise(); // ensure the change took place
   expect(newPieceOfState).toEqual(...);
   store.dispatch(/* dispatch UNAUTHENTICATED */);
   const state = await this.store.select(state => ....).pipe(take(1)).toPromise();
   expect(state).toEqual(...); // do your assertions that the meta reducer took effect and the state changed
});

在深入挖掘ngrx源代码后,我想出了一个测试它的方法

const invokeActionReducer = (currentState, action: any) => {
  return clearState((state) => state)(currentState, action);
};

it('should set state to initial value when logout action is dispatched', () => {
  const currentState = { /* state here */ };

  expect(invokeActionReducer(currentState, userUnauthenticated)).toBeFalsy();
});

Source