angulartypescriptunit-testingngrx-storengrx-router-store

NGRX Router pairwise unit test


does anybody have idea how to write unit tests for the below function? I spent a lot of time trying to find a solution, but without any result. The selectCurrentRoute is an ngrx router selector.

this.store
      .pipe(select(selectCurrentRoute), takeUntil(this.destroy), pairwise())
      .subscribe(([previousRoute, currentRoute]) => {
        if (previousRoute?.routeConfig?.path === 'login') {
          this.getSettings();
        }
      });

Thank you in advance!


Solution

  • Try something like this (This is Angular 5 and Ngrx 4):

    import { Component } from '@angular/core';
    import { routerReducer, RouterStateSerializer, StoreRouterConnectingModule } from '@ngrx/router-store';
    
    // MockComponent for the routes we will set up
    @Component({
      template: ``,
    })
    class MockComponent { }
    
    describe('Your component', () => {
      ....
      let store: Store<any>;
      let router: Router;
      
      beforeEach(async(() => {
       TestBed.configureTestingModule({
         imports: [
           RouterTestingModule.withRoutes(
             [{ path: '', component: MockComponent }],
           ),
           StoreModule.forRoot({
             router: routerReducer, // put ngrx router reducer how it is set up for your store
             // put other reducers as you see fit
           }),
           StoreRouterConnectingModule, 
         ],
         declarations: [MockComponent],
       }).compileComponent();
      }));
    
      beforeEach(() => {
        ....
        store = TestBed.get(Store);
        router = TestBed.get(Router); // this should be .inject instead of .get in Angular 9+
        ....
      });
    
      beforeEach(async done => {
        await router.navigate(['']); // two navigations so pairWise gets triggered
        await router.navigate(['']); // Angular testing may not allow two navigation, give it a try though
        done();
      });
    
      it('your test', () => {
        ....
      });
    
    });