NgRx Tips — Part 2 — Selectors and Testing

John Youngers
Youngers Consulting
2 min readJan 25, 2018

There are a couple of ways to select data from the store:

  1. Create selector functions:
export const getTodosState = createFeatureSelector<TodosState>('todos');
export const getTodosLoading = createSelector(getTodosState, (s) => s.loading);
...this.store.select(getTodosLoading);

2. ‘Pluck’ the values using strings:

this.store.select('todos', 'loading');

According to the documentation, using the first method should have some performance gains, but I’m not sure if it’s enough for me personally to use it over the second option (which requires less code). The downside is if you refactor property names in the state, they wouldn’t be updated in the string selectors; however, it would result in a compile error until the strings are corrected.

If you do use the second method, it’s easy to mock out the functionality of the store (assuming you’re confident enough in NgRx to completely exclude it from your tests) by creating a MockStore class:

MockStore should have you covered if you’re only selecting from the store (via strings) and dispatching actions.

In your test initialization you’d setup the initial section of state your component cares about, and in the actual tests you can then call update to directly change the state in various ways to verify your component is responding as expected.

NgRx provides some testing examples in their documentation if you’re looking to test with the actual store, but manipulating the state isn’t as direct (you’d need to include your reducers and dispatch various actions to get the state to your target).

If anyone has any insights on why it’s a good idea to use the selector functions over the strings, I’d be interested in hearing the reasoning: it seems like that’s the direction most demos/tutorials go; however, it also seems like they’re created out of a goal of completeness (selectors for every possible section of state) opposed to actual need.

In the next article I’ll revisit setting up features/actions.

--

--