Testing an NgRx project

Tim Deschryver

No intro needed, let's directly dive into some code snippets for each part of the Angular application! Each section includes a code snippet of the relevant part of the application, followed by one or more code snippets to see how we can test it efficiently. Some snippets also put a line in a spotlight (🔦) to showcase best practices.

Actions link

Let's start with the easiest one, which are the NgRx actions. I don't see any value to test these in isolation, instead, they are tested indirectly when we test the reducers and components.

Reducers link

A reducer is a (synchronous) pure function that is invoked with the current state and an action. Based on the state and the action, the reducer returns a new state.

Because a reducer is pure, and there are no external dependencies, the test specifications are very simple. There's no need to configure and mock anything, in a test we invoke the reducer with a predefined state and an action.

Given the state and the action, the assertion asserts that the newly returned state is correct.

Some practices I want to put in the spotlight:

🔦 The usage of the factory method to create new state entities. This creates a single point of entry when the structure of an object changes in the future. It also makes it easy to create an object in a good state, while you can still override the object in specific test cases.

🔦 Test data is assigned to variables (arrange). This data is used to invoke the reducer (act) and to verify the result (assert). Assigning test data to a variable prevents magic values, and later, failing tests when the data is changed.

Selectors link

NgRx selectors are pure functions to read a slice from the global store.

I categorize selectors into two groups, selectors that access raw data from the state tree, and selectors that merge data from multiple selectors from the first category and transform it into a useable model.

I never write tests for the selectors from the first category, and I rely on TypeScript to catch my silly mistakes.

The second category has logic in the selectors' projector to transform the data. It's this logic that is crucial to test.

To test these selectors there are two options:

  1. provide the full state tree to the selector, this also tests the logic of child selectors
  2. invoke the selector's projector method with input parameters, this only tests the project itself

The first option covers more production code, but in my experience, it also has a higher maintenance cost. That's why I prefer to use the latter.

A selector test isn't complex. The test invokes the selector's projector method with a given input and verifies its output.

Effects link

Effects handle all the side-effects of the application. These are usually asynchronous operations, for example an effect that makes an HTTP request.

Testing NgRx effects is where things are starting to get interesting because this is where, for the first time, (external) dependencies are involved.

To keep effect tests simple and fast, I prefer to not rely on the dependency container of Angular to provide and inject the dependencies with the Angular TestBed. Instead, I like to instantiate the new effect class manually and provide all of the dependencies myself. That also means that some dependencies are going to be mocked, In the next snippets I'm using jest to create mocks.

Most of the effect tests that I write are not using the marble diagram syntax to verify the output of an effect. This, not only to keep things as simple as possible but also because it makes sure that we test the right things. We want to test the effect flow, not the internal details of the effect implementation. Frankly said, we shouldn't care about which higher-order mapping operator is used, nor should we care if time-based operators are used to wait on a trigger, for example, the delay, throttle, and delay RxJS operators. We can assume that these behave as expected because these are tested within the RxJS codebase.

Effect tests can become complex, so let's start with a simple example to cover the basics. Afterward, we are going to explore some more advanced effect scenarios.

Effects that use Actions and Services link

The simple example covers the most common ground and makes an HTTP request when the effect receives an action. The effect class gets the Actions stream and a service (that acts as a wrapper around HTTP requests) injected into the effect class.

Before the fetch$ effect can be tested we need to create a new instance of the Effect class, which requires the Actions stream and a CustomerService.

Since the service is under our ownership, it's easy to create a mocked instance. This is needed to prevent the effect from calling the real service and making HTTP requests.

The Actions is a bit more complicated. Because it's a typed observable, it doesn't make it easy to be mocked. Spawning a new observable also doesn't provide a solution because we need to send actions to the effect during the test in order to trigger it. So what about using a Subject? This is a good choice, but it requires that we type the Subject to only accept actions, so it becomes Subject<Action>. While this works, it is not very convenient. Instead, I like to use the ActionsSubject stream (from @ngrx/store), which a typed Actions subject.

Now, we're able to create a new effect instance, and we can send actions to the effect under test. The only thing left before we can test the effect is to get the output of an effect. For that, we subscribe to the effect and capture the emitted actions.

Effect tests rewritten with observer-spy link

The above tests have a couple of drawbacks.

A minor drawback is that each test includes boilerplate code to catch the emitted actions. As a countermeasure, we can write a small utility method that catches all emitted actions.

But the major drawback is that the execution time of the test is affected by the time it takes to execute the effect. For effects that rely on time-based operators, this can be a problem. In its best case, this slows down the test. At its worst, it can lead to failing tests because the test exceeds the timeout limit.

Here's where the observer-spy library _- thanks to Shai Reznik for creating this library -_ comes into play. With observer-spy, we can subscribe to an observable stream, "flush" all pending tasks, and lastly, read the emitted values.

To use observer-spy in a test, we have to make small modifications to the test:

  1. subscribe to the effect with subscribeSpyTo
  2. if the test is time-sensitive, wrap the test callback with the fakeTime function
  3. if the test is time-sensitive, invoke the flush function to fast-forward the time and handle all pending jobs
  4. use the getValues function on the subscribed spy to verify the emitted actions

Effect tests and fake timers link

If bringing a library just for making these test easy is not your cup of tea, the other option is to use fake timers. This is a solution that isn't framework/library specific. The examples in this post are using Jest fake timers.

It looks similar to your "default" effect tests, but you get to play a time wizard because you'll have to advance the time by using your magic powers.

In contrast to observer-spy , where you need to subscribe on an Observable stream to flush all pending tasks, fake timers allows you to forward the time for all pending tasks. This is useful when you can't subscribe to a source, for example in a component.

With fake timers there are three possibilities to advance the time:

Some practices I want to put in the spotlight:

🔦 to make tests less brittle, wait for the pending task(s) to finish with runOnlyPendingTimers or runAllTimers instead of advancing the time with advanceTimersByTime. This makes sure that the test isn't impacted when the duration is modified.

Effects that don't dispatch actions link

So far we've seen effects that result in actions being dispatched, but as you probably already know, some effects don't dispatch an action (with the dispatch: false option).

To verify that these non-dispatching effects are doing what they're supposed to do, we can reuse 90% of a test, and modify the assertion. Instead of checking the emitted actions, we verify that a side-effect has been executed.

For example, the below test verifies that an action results in a notification.

To test that the dispatch config option is set to false we use the getEffectsMetadata method, which returns the configuration of all effects in a class. Next, we can access the config options of the effect we want to test, in this case, the done$ member.

Effects that use the NgRx Global Store link

NgRx v11 included a new method getMockStore (imported from @ngrx/store/testing) to new up a new mock store instance. This is perfect for our use case, as we can use getMockStore to prevent using the Angular TestBed for testing NgRx Effects. Meaning that we can keep the setup to all of our effects the same.

As an example, let's take an effect that only instantiates a new HTTP request for entities that are not in the store. To read from the store, the effect uses a selector to retrieve the entities from the store. The implementation of such an effect can be found in another blog post, Start using NgRx Effects for this.

The test below uses getMockStore to mock the ngrx store. getMockStore accepts a configuration object to "mock" the selectors. To do so, define the selectors that are used in the effect and assign them the desired return value.

When a return value is assigned to a selector, the logic of the selector isn't executed, but the given value is simply returned. The rest of the test remains untouched.

Effects that use the Angular Router link

Manually creating a new instance of the Router is difficult and tedious. Sadly, it also doesn't have a simple method to create a new instance outside of the Angular TestBed.

So how do we go about this? We could create a minimal implementation of the Router and just mock the methods that we need, or we could use a library that automatically creates spy implementations for all members and methods of a given type, in our example, the Router.

The test below verifies that the window's title is updated when the user navigates to a different route.

In the example, we use the createMock method from the Angular Testing Library (import from @testing-library/angular/jest-utils) to create a mock instance of the Title service.

The test also uses createMockWithValues to set a custom implementation for the router events. This way, we're able to emit new navigation events later to trigger the effect. The implementation of such an effect can be found in another blog post, Start using NgRx Effects for this.

The test below verifies that the window title is updated upon a router navigation.

Components With Global Store link

With most of the logic pulled outside of the component, we're left with a small component that doesn't require a lot of dependencies to be tested. There's also a big chance that you're splitting your components into two categories: containers, and presentational components.

In this post, we'll focus on containers because these are the ones that interact with the NgRx global store. If you want to become more familiar with testing presentational components, I got another post for you, Getting the most value out of your Angular Component Tests.

To test containers components, we again have two options.

One option is to treat a component test as an integration test. This means that real implementations of selectors, reducers, and effects are used, but that all communications with external services are mocked. Following the "don't test implementation details" best practice, this seems like the best option. But in this case, I would advise not to do it, because the test is going to be brittle and have a complex setup. The setup is hard because you have to configure the store, you need to know the details of all dependencies, and you have to maintain the state tree.

This is the opposite of what we're trying to achieve here. We want our test to help us develop and maintain an application, not a test that no one understands and wants to touch. Maintaining such a test might take up more time than developing new features.

The second option is to just test the component itself and the interaction with the store, a unit test. To verify the store interaction we use a mocked store because this prevents that reducers and effects are invoked.

From my experience, writing unit tests for container components is the most productive approach while we can still be confident in the code that we write. Because there are focussed unit tests on the reducers, selectors, effects, and containers the tests themselves are easier to reason about.

Testing a component requires, for the first time, the usage of the Angular TestBed.

Here again, we're using the Angular Testing Library. While the Angular Testing Library helps us to make the setup and the component interaction easier, it also guides us to create user-friendly components. A win-win situation for everyone.

To inject the store into the component, the provideMockStore method (imported from @ngrx/store/testing) is used and is configured as an Angular provider.

As an example, let's take a look at a component that displays a customer. The component reads the customer from the store with the selectCustomerWithOrders selector and displays the customer and the customer's orders on the page. There's also a refresh button that dispatches a customersPageActions.refresh action to the store.

The test to check that the customer's name is displayed correctly looks as follows. The important part here is that a mock store is provided, and while doing so, that the selector is provided a mocked return value. This prevents that we have to configure the whole store, and we can simply provide what is needed. This keeps the test readable and compact.

Some practices I want to put in the spotlight:

🔦 toBeVisible is a custom jest matcher from jest-dom

🔦 Testing With SIFERS by Moshe Kolodny to promote test setups

The above example verifies that the component renders correctly. Next, we'll see how we can assert that an action is dispatched to the store, in this example when the refresh button is clicked.

To assert that the component sends the refresh action to the store, we're assigning a spy to the dispatch method of the store. We use this spy in the assertion to verify that the action is dispatched.

Component Store link

In contrast with the global NgRx store, a component store is strongly coupled to the component. That's the reason why I prefer to see the component store as an implementation detail and thus I almost don't mock the component store during tests. Because the test is using the real implementation of the component store some of the dependencies of the component store must be mocked to prevent communication with the external world.

In the following example, there's a CustomersSearchStore that is used in the CustomersSearchPageComponent component. The store holds the customers' state and makes an HTTP request to fetch the customers. The component uses the store to render the customers in the view.

To get to know the difference between an integration test and a unit test, we're going to write the same tests for the component.

Integration tests link

The integration test verifies that the component and the component store are integrated correctly. If you've followed the examples in the previous sections, the next test is going to read easily.

The component test is written with the help of Angular Testing Library. During the setup, we provide a mock for the CustomersService service, which is a dependency from the component store. For the rest of the test, we replicate a user interaction with the store and assert that the right things are rendered. Because the search query has a delay, the test uses Jest fake timers to forward the elapsed time.

These kinds of tests tend to be longer than you're used to and these are going to verify multiple assertions. This is totally fine. It's even desired to write tests like this if you're using the (Angular) Testing Library.

Unit tests link

For component stores that are complex and/or require more dependencies, it might be easier and better to unit test the component store and the component separately. Doing this makes it easier to test specific cases. The test suite also going to run faster because the component doesn't need to be rendered to execute component store tests, of which you will write most specifications.

Just like testing the global store, you only write a few component tests that rely on a component store. These make sure that the interaction between the component and the component store is correct.

Component store unit tests link

You're going to write many (small) tests to make sure that each method of the component store behaves correctly. Most of them are updating the state of the component store to assert that the state is in the correct shape.

Component unit tests that use the component store link

In comparison to component store tests, we only have a few component tests that rely on the component store. These tests are also smaller in comparison to the component tests that use the real implementation of the component store. Instead of using the real implementation of the component store, the component store is mocked during the setup. Because the component store is provided at the component level, the mocked store instance needs to be provided in the componentProviders array.

The component tests can be divided into two groups, one that renders the current state, and the other that invoke component store methods.

For the first group, we assign a predefined result to the select members of the component store. After the component is rendered, the test takes a look at the component and verifies that the view is correct.

The second group of tests are assigning spies to the component store methods, which are used to check that the component store method is invoked after interacting with the component.

Conclusion link

Writing tests for an Angular application doesn't have to be a chore. When the tests are written correctly, they are used to verify the correctness of the application while they don't hold you back on building new features or changing existing features.

For me, the ideal test is a test that mocks as little as possible and keeps the setup simple. This makes sure that the test is easier to maintain.

To make the tests in this post as simple as possible, the Angular TestBed is avoided.

Reducers are called with a predefined state and an action in the test. The test then verifies that the returned state is correct.

Selectors that contain logic are tested with the projector method. Instead of providing the state tree and invoking child selectors, we invoke the projector with the return values of the child selectors. The result is then asserted against the expected value.

Effect tests are written without the Angular TestBed. We create the effect instance manually and mock its dependencies. The effect that is being tested is subscribed to catch all of the emitted actions, which are then checked. To trigger the effect we send a new action to the ActionsSubject.

Components that use the global store are tested with the help of the Angular Testing Library. In component tests, we don't use the real store instead, but we use a mocked store.

Components with the component store have two kinds of tests, unit tests, and integration tests. I prefer to write integration tests, but when they become too complex, I prefer to write unit tests. Integration tests use the real store and mock the component store dependencies. Unit tests are written on the component store, and additionally on the component while providing a mocked component store instance.

Happy testing!

Incoming links

Outgoing links

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at ko-fi.com PayPal logo

Share this post on

Twitter LinkedIn