Angular 2 Mocking @ngrx/Store

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

@ngrx/Store is becoming more widely used in Angular 2 projects. As such, the Store is required to be injected into the constructor of any Component or Service that wishes to use it. Unit testing Store isn't as easy as testing a simple service though. As with many problems, there are a myriad of ways to implement solutions. However, the basic recipe is to write a mock class for the Observer interface and to write a mock class for Store. Then you can inject Store as a provider in your TestBed.

Parameters

namedescription
valuenext value to be observed
errordescription
errerror to be thrown
superdescription
action$mock Observer that does nothing unless defined to do so in the mock class
actionReducer$mock Observer that does nothing unless defined to do so in the mock class
obs$mock Observable

Remarks

Observer is a generic, but must be of type any to avoid unit testing complexity. The reason for this complexity, is that Store's constructor expects Observer arguments with different generic types. Using any avoids this complication.

It's possible to pass null values into StoreMock's super constructor, but this restricts the number of assertions that can be used to test the class further down the road.

The Component being used in this example is just being used as context for how one would go about injecting Store as a provide in the test setup.



Got any Angular 2 Question?