lundi 10 février 2020

How to test ngrx store action dispatch on route params change?

I am testing a component which displays some data from ngrx store, when button is clicked.

On button click, the route params change

  <button
    class="submit"
    [routerLink]="['/page']"
    [queryParams]="{
      period_start: '01.01.19',
      period_end: '01.01.19',
      submit_search: '->'
    }"
  >
  </button>

I subscribe to the change in route params on init and dispatch a store action, if one of the params is submit_search.

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      if (params.submit_search) {
        this.store.dispatch(...);
      }
    });
  }

This test knows that route after click has changed (this test passes):

    it('should set route params to filter params', fakeAsync(() => {
      const filterButtonElement = fixture.nativeElement.querySelector('.submit');
      filterButtonElement.click();
      tick();
      expect(location.path()).toEqual(
        `'/page?period_start=01.01.19&period_end=01.01.19&submit_search=-%3E'`
      );
    }));

But this test says that 'dispatch' has been called 0 times:

describe('SomeComponent', () => {
  let dispatchSpy;
  let location: Location;
  let router: Router;
  let route: ActivatedRoute;
  let component: SomeComponent;
  let fixture: ComponentFixture<SomeComponent>;
  let mockStore: MockStore<State>;
  let mockGetData: MemoizedSelector<State, SomeData[]>;
  const initialState = {};
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        RouterTestingModule.withRoutes([
          {
            path: 'page',
            component: SomeComponent
          }
        ]),
      ],
      declarations: [SomeComponent],
      providers: [
        provideMockStore({ initialState }),
        { provide: ActivatedRoute, useValue: { queryParams: from([]) } }
      ]
    }).compileComponents();
    router = TestBed.get(Router);
    route = TestBed.get(ActivatedRoute);
    location = TestBed.get(Location);
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(SomeComponent);
    component = fixture.componentInstance;
    mockStore = TestBed.get(Store);
    mockGetData = mockStore.overrideSelector(SomeSelectors.selectData, []);
    router.initialNavigation();
    fixture.detectChanges();
  });
    it('should dispatch store action', fakeAsync(() => {
      dispatchSpy = spyOn(mockStore, 'dispatch');
      const filterButtonElement = fixture.nativeElement.querySelector('.submit');
      filterButtonElement.click();
      tick();
      expect(dispatchSpy).toHaveBeenCalledTimes(1);
    }));
});

Why does it think, that the action wasn't dispatched?

Aucun commentaire:

Enregistrer un commentaire