Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active October 11, 2020 20:28
Show Gist options
  • Save ivankisyov/2a4719747e294e9fcd7b3f2a8bd1de3f to your computer and use it in GitHub Desktop.
Save ivankisyov/2a4719747e294e9fcd7b3f2a8bd1de3f to your computer and use it in GitHub Desktop.
NGRX Testing Principles

NGRX Testing Principles

Testing reducer:

  • pass state and action and expect on the result

Testing selector:

  • use projector method of a selector and pass some stubbed state to it and expect on the result

Testing effects:

  • provide mockStore, passing initial state
  • provide mockActions, with a callback returning actions that you define in the tests
  • use testScheduler and use its hot/cold helpers to create streams
  • use hot/cold helpers to set the action stream to a specific action being emitted
  • use a mock service and set the return value of a specific method, which is used by the effect, to return a cold observable containing the response
  • use expectObservabe(effects.getAllShows$).toBe('--b', {b: outcome})
  // -a -> action emission
  //  -b -> response from service
  // --b -> observable from effect

Testing components:

Verify that dispatch is being called

  • use mockStore
  • spyOn(store, 'dispatch')
  • call component's method which internally should dispatch action
  • expect that spy was called with proper action

Verify that select method correctly sets the view model

describe('selectors', () => {
    let mockShowsSelector;
    beforeEach(() => {
      mockShowsSelector = store.overrideSelector(selectFavoriteShows, [{
        id: 3,
        name: 'C',
        description: 'Show C',
        imgUrl: '',
        isFavorite: true
      }]);
      fixture.detectChanges();
    });

    it('should render all favorite shows', () => {
      expect(fixture.debugElement.queryAll(By.css('.mat-card')).length).toBe(1);
    });

    it('should update the UI when the selector changes', () => {
      mockShowsSelector.setResult([
        {
          id: 1,
          name: 'A',
          description: 'Show A',
          imgUrl: '',
          isFavorite: true
        },
        {
          id: 2,
          name: 'B',
          description: 'Show B',
          imgUrl: '',
          isFavorite: true
        }
      ]);
      store.refreshState();
      fixture.detectChanges();
      expect(fixture.debugElement.queryAll(By.css('.mat-card')).length).toBe(2);
    });
  })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment