Search code examples
angularngrxngrx-storengrx-effectsangular-test

NgRx Selectors not Working in Effects Unit Test


I am writing unit tests for my NgRx Effects (Resource: https://ngrx.io/guide/effects/testing). But I have a problem with the withLatestFrom. When selecting a slice of my state via an selector (e.g.: this.store.select( mySelectors.selectId )), the test throws an error:

zone.js:199 Uncaught TypeError: Cannot read property 'id' of undefined
    at :9876/_karma_webpack_/webpack:/src/app/root-store/my-store/my.selectors.ts:13
    at :9876/_karma_webpack_/webpack:/node_modules/@ngrx/store/fesm5/store.js:504
    at memoized (:9876/_karma_webpack_/webpack:/node_modules/@ngrx/store/fesm5/store.js:454)
    at defaultStateFn (:9876/_karma_webpack_/webpack:/node_modules/@ngrx/store/fesm5/store.js:473)
    at :9876/_karma_webpack_/webpack:/node_modules/@ngrx/store/fesm5/store.js:507
    at memoized (:9876/_karma_webpack_/webpack:/node_modules/@ngrx/store/fesm5/store.js:446)
    at MapSubscriber.project (:9876/_karma_webpack_/webpack:/node_modules/@ngrx/store/fesm5/store.js:401)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm5/internal/operators/map.js:35)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm5/internal/Subscriber.js:53)
    at MockState.push../node_modules/rxjs/_esm5/internal/BehaviorSubject.js.BehaviorSubject._subscribe (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm5/internal/BehaviorSubject.js:22)

But when I am not using my own selector but rather something like this: this.store.select( state => state.id ), the test passes.

Effect

myEffect$ = createEffect( () =>
  this.actions$.pipe(
      ofType( myActions.myAction ),
      withLatestFrom(
          // this doesn't work
          this.store.select( mySelectors.selectId ),
          // this works
          // this.store.select( state => state.id ),
      ),
      switchMap( ( [action, id] ) => { /* ... */  } )
  )
);

Selector

export const selectMyState = createFeatureSelector<MyState>( 'feature' );

export const selectId = createSelector(
    selectMyState,
    ( state: MyState ) => state.id
);

Test

describe( 'My Effects', () => {
    let effects: MyEffects;
    let actions: ReplaySubject<any>;
    let store: MockStore<MyState>;

    beforeEach( () => {
        TestBed.configureTestingModule( {
            imports: [HttpClientModule, RouterTestingModule],
            providers: [
                MyEffects,
                provideMockActions( () => actions ),
                provideMockStore( { initialState: fromMy.initialState } ),
                MyService,
            ]
        } );
        TestBed.overrideProvider( MyService, { useValue: new MyMockService() } );

        effects = TestBed.get<MyEffects>( MyEffects );
        store = TestBed.get<Store<RootStoreState.State>>( Store );
    } );

  it( '#myEffect$ should work', () => {
      actions = new ReplaySubject( 1 );
      store.setState( { /* ... */ } );
      actions.next( myActions.myAction() );
      effects.saveEditMy$.subscribe( result => {
          expect( result ).toEqual( myActions.myActionDone( { /* ... */ } ) );
      } );
  } );
} );

MyState Interface

export interface MyState extends EntityState<MyEntity> {
    loading: boolean;
    loaded: boolean;
    error: string;
    buttonStates: string[];
    id: string;
    edit: boolean;
    formData: Partial<MyEntity>;
    isFormValid: boolean;
    isDeletePopupVisible: boolean;
}

Solution

  • Try to override selector:

    provideMockStore({
      initialState: fromMy.initialState,
      selectors: [
        {
          selector: mySelectors.selectId,
          value: 1 // your id
        }
      ]
    })
    

    Edit 1:

    Update selector value in different test cases:

    store.overrideSelector(mySelectors.selectId, 3); // your id
    

    Edit 2:

    The case was different here, state in mySelectors.selectId was undefined because it comes from feature selector which is feature so setState should be called like this:

    store.setState({feature:{id: 2}});