Unit Testing

Unit testing is easy with NGXS. To perform a unit test we just dispatch the events, listen to the changes and perform our expectation. A basic test looks like this:

import { TestBed } from '@angular/core/testing';

describe('Zoo', () => {
  let store: Store;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [NgxsModule.forRoot([ZooState])]
    });

    store = TestBed.inject(Store);
  });

  it('it toggles feed', () => {
    store.dispatch(new FeedAnimals());

    const feed = store.selectSnapshot(state => state.zoo.feed);
    expect(feed).toBe(true);
  });
});

We recommend using selectSnapshot method instead of selectOnce or select. Jasmine and Jest might not run expectations inside the subscribe block. Given the following example:

Prepping State

Often times in your app you want to test what happens when the state is C and you dispatch action X. You can use the store.reset(MyNewState) to prepare the state for your next operation.

Note: You need to provide the registered state name as key if you reset the state. store.reset will reflect to your whole state! Merge the current with your new changes to be sure nothing gets lost.

Testing Selectors

Selectors are just plain functions that accept the state as the argument so its really easy to test them. A simple test might look like this:

In your application you may have selectors created dynamically using the createSelector function:

Testing these selectors is really an easy task. You just need to mock the state and pass it as parameter to our selector:

Testing Asynchronous Actions

It's also very easy to test asynchronous actions using Jasmine or Jest. The greatest features of these testing frameworks is a support of async/await. No one prevents you of using async/await + RxJS toPromise method that "converts" Observable to Promise. As an alternative you could have a done callback, Jasmine or Jest will wait until the done callback is called before finishing the test.

The below example is not really complex, but it clearly shows how to test asynchronous code using async/await:

Last updated