Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Unit Test Component with Store dispatch action

I have a component that has the following function:

onClearSearch() {
  this.store$.dispatch(some action);
}

Trying to unit test the component and trigger the store dispatch is not working. My component test looks like this:

let store: MockStore<State>;

beforeEach(waitForAsync(() => {
  TestBed.configureTestModule({
    ...
    providers: [
      SearchStoreEffects,
      provideMockActions(() => actions$),
      provideMockStore({initialState, selectors: [...]})
    ],
    ...
  }).compileComponents();

  ...
  store = TestBed.inject(MockStore);
  fixture.detectChanges();
}));

it('should clear search value', () => {
  const storeSpy = spyOn(store, 'dispatch').and.callThrough();
  component.onClearSearch();
  fixture.detectChanges();
  expect(storeSpy).toHaveBeenCalledTimes(1);
});

The test always fails with test has been called zero times. What am I missing?

like image 799
tlavarea Avatar asked Sep 08 '26 19:09

tlavarea


1 Answers

You need to spy on the component instance

it('should clear search value', () => {
  const storeSpy = spyOn(component.store$, 'dispatch').and.callThrough();
  component.onClearSearch();
  fixture.detectChanges();
  expect(storeSpy).toHaveBeenCalledTimes(1);
});
like image 80
Owen Kelvin Avatar answered Sep 10 '26 10:09

Owen Kelvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!