Search code examples
angularkarma-jasminengrx

How to test this specific selector?


I'm testing my NgRx code, on my selectors I have two selectors:

export const selectSlice = (state: AppState) => state.slice;

export const selectErrors = createSelector(
  selectSlice,
  state => state.errors
);

I can test selectErrors pretty easily with projector but I can't test the first one, it always stays as "function uncovered" on Instanbul. I tried the following:

it('should return call to selectSlice', () => {
    const selector = selectors.selectSlice;
    store.select(selector);

    expect(store.select).toHaveBeenCalledWith(selector);
});

How am I supposed to test it?

Edit: This is my test for the errors selector:

it('should return call to selectErrors', () => {
    const selector = selectors.selectErrors;
    store.select(selector);

    expect(store.select).toHaveBeenCalledWith(selector);
    expect(
      selector.projector({
        errors: [
          {
            message: 'Mock error'
          }
        ]
      }).length
    ).toEqual(1);
  });

Solution

  • The function is uncovered because you're using the selector's projector function which skips executing the selectors and only runs the projector function.

    To get codecoverage for it, you should:

    • not use the projector function as it's a fairly simple selector
    • or write a test for it as follows (because a selector is just a function, you can invoke it and test the output):
    expect(selectSlice({ slice: 'foo'})).toEqual('foo')
    

    Personally, I don't see any added value to writing these tests and these might be time consuming - see my article How I test my NgRx selectors for more info.