Search code examples
angularunit-testingcode-coveragengrxngrx-store

How to test the ngrx store.select of an Observable, in angular5?


I would like to understand what is missing in the test to cover the file I'm working at, in order to achieve 100% coverage. Here are the parts under attention:

Given this typescript file:

constructor(
  public store: Store<AppState>
) {}

ngOnInit(): void {
  this.search$ = this.store.select(s => s.search);
}

And this test:

it('should start observing the search store', () => {
  const search: any = {
    data: {}
  };
  const state = Observable.of(search);

  const store = jasmine.createSpyObj('store', ['select']);
  store.select.and.returnValue(state);
  component.store = store;

  component.ngOnInit();

  expect(component.search$).toBe(state);
});

Current test coverage:

enter image description here

I guess what I'm missing is something very stupid I blindly do not see it. Thanks for helping in advance.


Solution

  • Indeed as @shaunhusain suggested, this was the fix for the file

    ngOnInit(): void {
      this.fetch();
      this.search$ = this.store.select(this.getStoreSearchData);
    }
    
    private getStoreSearchData(store: AppState): Search {
      return store.search;
    }
    

    and its test:

    describe('#getStoreSearchData', () => {
      it('should return the search store', () => {
        const search: any = {
          data: {}
        };
    
        const store = <AppState>{search: search};
    
        const storeSearch = component['getStoreSearchData'](store);
    
        expect(storeSearch).toEqual(search);
      });
    });    
    

    and now coverage is back to 100%