Angular 2Mocking @ngrx/Store

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

name

description

value

next value to be observed

error

description

err

error to be thrown

super

description

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.